C Variable Scope

C Tutorial

C Variable Scope

Variable scope in C language defines where a variable can be accessed or used in a program.
Understanding scope is critical for debugging, memory management, and interviews.


 What is Variable Scope?

Variable scope determines the visibility and lifetime of a variable.

In C, scope is mainly divided into:

  1. Local scope

  2. Global scope

  3. Block scope

  4. Function parameter scope

  5. Static scope (special case)


 Local Variable Scope

 Definition

  • Declared inside a function

  • Accessible only within that function

  • Destroyed after function execution

Example


 

  • x is visible only inside show()

 Global Variable Scope

 Definition

  • Declared outside all functions

  • Accessible by all functions

  • Lifetime = entire program execution

Example


 

  •  Overuse of globals is not recommended

 Block Scope {}

 Definition

Variables declared inside { } are accessible only within that block.

Example


 

  • y exists only inside if block

 Function Parameter Scope

 Definition

  • Function parameters act as local variables

  • Accessible only inside the function

Example


 

  • a exists only inside print()

 Static Variable Scope (Very Important)

Definition

  • Declared using static

  • Scope is local, but lifetime is entire program

Example


 

 Output:

1
2
3
  •  Value is retained between function calls

 Scope vs Lifetime (Interview Favorite)

TermMeaning
ScopeWhere variable is accessible
LifetimeHow long variable exists

Example


 Variable Shadowing

 Definition

When a local variable hides a global variable with the same name.

Example


 

 Output: 50 

  •  Global x still exists but is hidden

 Storage Class & Scope Relation

Storage ClassScopeLifetime
autoLocalFunction
registerLocalFunction
staticLocal / GlobalProgram
externGlobalProgram

 Common Mistakes

  •  Using local variable outside function
  •  Confusing scope with lifetime
  •  Overusing global variables
  •  Shadowing variables unintentionally

 Interview Questions (Must Prepare)

  1. What is variable scope?

  2. Difference between local and global variables

  3. What is block scope?

  4. Static variable scope and lifetime

  5. What is variable shadowing?

  6. Scope vs lifetime difference


 Real-Life Importance

  • Prevents bugs

  • Improves code readability

  • Essential for multi-file projects

  • Important for embedded & system programming


 Summary

  •  Scope defines where variable can be used
  •  Lifetime defines how long it exists
  •  Local variables are safer than globals
  • static variables retain value
  •  Very important for interviews & real projects

You may also like...