C Variable Scope

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:
Local scope
Global scope
Block scope
Function parameter scope
Static scope (special case)
Local Variable Scope
Definition
Declared inside a function
Accessible only within that function
Destroyed after function execution
Example
xis visible only insideshow()
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
yexists only insideifblock
Function Parameter Scope
Definition
Function parameters act as local variables
Accessible only inside the function
Example
aexists only insideprint()
Static Variable Scope (Very Important)
Definition
Declared using
staticScope is local, but lifetime is entire program
Example
Output:
- Value is retained between function calls
Scope vs Lifetime (Interview Favorite)
| Term | Meaning |
|---|---|
| Scope | Where variable is accessible |
| Lifetime | How long variable exists |
Example
Variable Shadowing
Definition
When a local variable hides a global variable with the same name.
Example
Output: 50
- Global
xstill exists but is hidden
Storage Class & Scope Relation
| Storage Class | Scope | Lifetime |
|---|---|---|
auto | Local | Function |
register | Local | Function |
static | Local / Global | Program |
extern | Global | Program |
Common Mistakes
- Using local variable outside function
- Confusing scope with lifetime
- Overusing global variables
- Shadowing variables unintentionally
Interview Questions (Must Prepare)
What is variable scope?
Difference between local and global variables
What is block scope?
Static variable scope and lifetime
What is variable shadowing?
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
staticvariables retain value- Very important for interviews & real projects
