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.
1️⃣ 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)
2️⃣ Local Variable Scope
🔹 Definition
-
Declared inside a function
-
Accessible only within that function
-
Destroyed after function execution
Example
✔ x is visible only inside show()
3️⃣ Global Variable Scope
🔹 Definition
-
Declared outside all functions
-
Accessible by all functions
-
Lifetime = entire program execution
Example
⚠️ Overuse of globals is not recommended
4️⃣ Block Scope {}
🔹 Definition
Variables declared inside { } are accessible only within that block.
Example
✔ y exists only inside if block
5️⃣ Function Parameter Scope
🔹 Definition
-
Function parameters act as local variables
-
Accessible only inside the function
Example
✔ a exists only inside print()
6️⃣ Static Variable Scope ⭐ (Very Important)
🔹 Definition
-
Declared using
static -
Scope is local, but lifetime is entire program
Example
✔ Output:
📌 Value is retained between function calls
7️⃣ Scope vs Lifetime (Interview Favorite ⭐)
| Term | Meaning |
|---|---|
| Scope | Where variable is accessible |
| Lifetime | How long variable exists |
Example
8️⃣ 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
9️⃣ 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
✔ static variables retain value
✔ Very important for interviews & real projects
