Where a variable is declared affects where it can be used and how long its stored value exists. Local variables belong to a block or function, file-scope variables can be accessed by functions in that translation unit, and a local static variable keeps its value between calls.
#include <stdio.h>
int value = 5;
void update_value(void) {
printf("Inside function: %d\n", value);
value++;
}
int main(void) {
printf("Before calls: %d\n", value);
update_value();
update_value();
printf("After calls: %d\n", value);
return 0;
}
Output
Before calls: 5
Inside function: 5
Inside function: 6
After calls: 7
The file-scope variable is the same object each function accesses, so changes remain visible after the function returns.
#include <stdio.h>
int value = 5;
void show_local(void) {
int value = 10;
printf("Local value: %d\n", value);
value++;
}
int main(void) {
show_local();
show_local();
printf("Global value: %d\n", value);
return 0;
}
Output
Local value: 10
Local value: 10
Global value: 5
Each call creates a new automatic local value. It hides the file-scope variable while execution is inside show_local().
Key change: add static to the local declaration.
void show_count(void) {
static int count = 10;
printf("%d\n", count);
count++;
}
When called twice, the output is:
10
11
A block-scope static variable is visible only in that block, but its lifetime lasts for the entire program execution.
main() and the helper function can modify it.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.