5.2 Scope and Storage Duration
Scope decides where a name is visible. A variable declared inside a function or block is local.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
// i cannot be used hereFunction parameters are local variables too. When a function is called, argument values are copied into parameters, so changing a parameter does not automatically change the caller's variable.
A classic example is swap(): it tries to exchange two variables inside a function, but fails.
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main(void) {
int x = 3, y = 8;
swap(x, y);
printf("%d %d\n", x, y);
return 0;
}Output:
3 8swap() only exchanges its own local copies a and b; x and y in main never change. To really swap the caller's variables, you must pass their addresses (pointers), which Chapter 7 introduces.
A global variable is declared outside functions and can be accessed by functions in the file. It lives longer, but it can make data changes harder to trace. Prefer local variables and parameters first.
A static local variable keeps its value between calls, but its name is still only visible inside the function.