C Variable Scope
1. What is Variable Scope?
-
Scope defines the region of a program where a variable can be accessed or modified.
-
Variables in C can be local, global, or static, each with different visibility.
2. Types of Variable Scope
A) Local Variables
-
Declared inside a function or block.
-
Accessible only within that function or block.
-
Destroyed when the function/block ends.
Example:
Output:
B) Global Variables
-
Declared outside all functions (usually at the top).
-
Accessible by all functions in the same file.
Example:
Output:
C) Static Variables
-
Declared using
statickeyword inside a function. -
Retains value between function calls.
-
Scope is local to the function, but lifetime is throughout the program.
Example:
Output:
Without
static,countwould reset to 0 on each call.
D) Block Scope
-
Variables declared inside
{}are only valid within that block.
E) Function Parameters
-
Function parameters are local to that function.
3. Summary Table of Variable Scope
| Variable Type | Scope | Lifetime | Example |
|---|---|---|---|
| Local | Inside function/block | Function/block ends | int x inside function |
| Global | Entire file/functions | Entire program | int g = 10; at top |
| Static (local) | Inside function | Entire program | static int count = 0; |
| Function parameter | Inside function | Function call ends | void f(int n) |
4. Key Points
-
Local variables are created and destroyed each function call.
-
Global variables are accessible anywhere in the file.
-
Static variables retain their value across multiple calls.
-
Use minimal global variables to avoid unexpected modifications.
-
Function parameters are also local variables with values passed from the caller.
