Lesson 24: Scope Rules: Local and Global Variables
Scope defines the region of the program where a declared identifier (variable, function, etc.) can be accessed.
1. Local Scope (Automatic Variables)
- Variables declared inside a function, block (
{}), or as function parameters. - Their scope is limited to that block.
- They are created when the block is entered and destroyed when the block is exited.
c void example_func() { int x = 10; // Local to example_func if (x > 5) { int y = 20; // Local to the if block printf("y is %d\n", y); } // y is destroyed here // printf("y is %d\n", y); // ERROR: y is out of scope }
2. Global Scope (External Variables)
- Variables declared outside of any function.
- Their scope extends from the point of declaration to the end of the file.
- They can be accessed and modified by any function in the program (and potentially other files).
c int GLOBAL_COUNTER = 0; // Global variable
void increment() { GLOBAL_COUNTER++; // Accessible here }
int main() { increment(); printf("Counter: %d\n", GLOBAL_COUNTER); // Accessible here return 0; }
Storage Classes (Brief Mention)
Storage class specifiers like auto, extern, static, and register control the scope, lifetime, and linkage of variables. We will focus on static later, which allows a variable to retain its value between function calls, even if defined locally.