Scope of Variables (Lesson)
Scope and Visibility of Variables
The scope of a variable determines where in the program that variable is accessible. In C, we generally deal with two main types of scope.
11.1 Local Scope
A variable declared inside a function or a block { } is local to that block.
- Visibility: Only visible within the defining block.
- Lifetime: Created when the block is entered and destroyed when the block is exited.
- Precedence: If a local variable has the same name as a global variable, the local variable takes precedence.
void myFunction() {
int x = 5; // Local variable
printf("%d", x);
}
// printf("%d", x); // Error! x is unknown here.
11.2 Global Scope
A variable declared outside all functions is global.
- Visibility: Visible to all functions following its declaration in that file.
- Lifetime: Exists for the entire duration of the program.
- Usage: Useful for data that needs to be accessed by many functions.
int globalCount = 0; // Global variable
void increment() { globalCount++; }
void decrement() { globalCount--; }
11.3 Block Scope
Variables can also be localized to specific structures like loops or if statements.
for (int i = 0; i < 10; i++) { // 'i' exists only inside this for loop
printf("%d", i);
}
// printf("%d", i); // Error! 'i' is out of scope.
11.4 Formal Parameters
Variables in a function definition (arguments) are also treated as local variables within that function.
void add(int a, int b) { // 'a' and 'b' are local to add()
printf("%d", a + b);
}
Example: Scope Precedence
#include <stdio.h>
int x = 50; // Global
int main() {
int x = 10; // Local
printf("X in main: %d\n", x); // Prints 10 (local shadows global)
return 0;
}
Refer to the Lecture Slides for visual diagrams explaining the Symbol Table and memory segments.