The variable scope in C defines the section of code where a variable is accessible for use. Historically, since the early versions of the C language, support for local and global scopes has allowed for structured programs, reduced the number of errors due to variable shadowing, and improved code readability.
Problem: Without a proper understanding and use of variable scope, issues such as accidental variable shadowing, difficulties in code maintenance and scaling, as well as bugs related to the non-obvious behavior of variables can arise.
Solution: Correctly use different scopes: block scope (within curly braces), function scope, file scope (using static), and global scope. This minimizes the impact of one part of the code on another and reduces the likelihood of side effects.
Example code:
int global_var = 10; void foo() { int block_var = 5; if (block_var > 3) { int inner_var = 2; printf("inner_var: %d\n", inner_var); } // inner_var is not accessible here — out of its block }
Key features:
Can you access a local variable from another function via a pointer?
Only if you return the address of the variable, for example returning the address of a local variable from a function, but this leads to undefined behavior as the local variable's memory may be overwritten after the function completes.
Example code:
int* bad_function() { int temp = 42; return &temp; // dangerous! }
What happens when declaring two variables with the same name in different scopes?
The shadowing rule will apply: the closer variable to the point of use will hide all others with the same name that are higher in the scope hierarchy.
Example code:
int value = 100; // global void foo() { int value = 10; // local, hides global }
How does the static specifier affect the scope of a variable in different declaration contexts?
If static is used for a variable inside a function, it becomes local with its value retained between calls (block lifetime and block visibility). If static is for a global variable, its visibility is limited to the current file (file scope).
In a large project, all variables are declared globally. Someone accidentally overwrites a global variable from another function, and the program works incorrectly only under certain function call orders.
Pros:
Cons:
In each function, only local variables are used, and the necessary data is passed through function parameters.
Pros:
Cons: