C Scope
The scope of a variable is the part of the program where its name can be used. Scope keeps variables of different functions apart, so each function can use names like i or total without disturbing the others.
Local variables
A variable declared inside a function is local: it exists only inside that function, from its declaration to the closing brace. Another function cannot see it, and it disappears when the function returns.
#include <stdio.h>
void counter(void) {
int count = 0; // a new count every call
count++;
printf("count = %d\n", count);
}
int main(void) {
counter();
counter();
return 0;
}count = 1 count = 1
Each call creates a fresh count, so the output is 1 both times. The Storage Classes topic shows how static makes a local variable keep its value between calls.
Block scope
A variable declared inside any block, such as a loop or an if, exists only in that block:
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 3; i++) {
int square = i * i; // only inside the loop
total += square;
}
// i and square do not exist here
printf("total = %d\n", total);
return 0;
}total = 14
Global variables
A variable declared outside all functions is global: every function in the file can use and change it.
#include <stdio.h>
int score = 0; // global
void addPoints(int p) {
score += p;
}
int main(void) {
addPoints(10);
addPoints(5);
printf("score = %d\n", score);
return 0;
}score = 15
Globals look convenient, but any function can change them, so when the value is wrong it is hard to find out who changed it. Prefer passing values as parameters and returning results; keep globals for things that really belong to the whole program.
Shadowing
A local variable may have the same name as a global one. Inside its scope the local one hides (shadows) the global one. This is legal but confusing; give them different names.
Practice exercises
- Write a function that uses a local variable with the same name as a variable in
main, and show that they are independent. - Rewrite the score example without a global:
addPointsshould take the score and return the new score. - Try to print a loop variable after the loop and read the error.