C Scope
Scope decides where a name works in a program. A local variable lives inside one function, and a global variable lives outside all functions.
A global variable
bonus sits outside all functions. print_bonus reads it, so the print shows 10.
#include <stdio.h>
int bonus = 10;
void print_bonus(void) {
printf("%d\n", bonus);
}
int main() {
print_bonus();
return 0;
}A local variable
x lives inside show, and only show can use it. The print shows 7.
#include <stdio.h>
void show(void) {
int x = 7;
printf("%d\n", x);
}
int main() {
show();
return 0;
}Shadowing in action
The global score holds 100, and the local score inside show holds 5. show prints 5, its own score, and main prints 100, the global one.
#include <stdio.h>
int score = 100;
void show(void) {
int score = 5;
printf("%d\n", score);
}
int main() {
show();
printf("%d\n", score);
return 0;
}Example
#include <stdio.h>
int level = 1;
void play(void) {
int level = 9;
printf("%d\n", level);
}
int main() {
play();
printf("%d\n", level);
return 0;
}Key points
- A local variable is created inside a function.
- A local variable can be used only inside its own function.
- Each function has its own local variables, even when the names match.
- A global variable is created outside all functions.
- A global variable can be used in every function.
- A function can read a global variable and give it a new value.
- Shadowing is when a local variable has the same name as a global variable.
- Inside that function, the local name hides the global one.
- Outside that function, the global name works as before.
The global level holds 1, and the local level inside play holds 9. Play prints its own level first, so 9 prints first. Then main prints the global level, so 1 prints next.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which variable can be used in every function?