Scope determines where a variable can be accessed. Understanding scope helps you reason about variables inside and outside functions.
Local variables
Variables defined inside a function are local variables. They can only be accessed inside that function.
#include <stdio.h>
void swap(int a, int b) {
int temporary = a;
a = b;
b = temporary;
printf("inside swap(): %d %d\n", a, b);
}
int main(void) {
int a = 1;
int b = 2;
printf("Before: %d %d\n", a, b);
swap(a, b);
printf("After: %d %d\n", a, b);
return 0;
}Output:
Before: 1 2
inside swap(): 2 1
After: 1 2Two rooms, two pairs of boxes
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
File-scope variables and static
A variable declared outside every function has file scope. Adding static keeps that name private to the current source file while allowing functions in that file to share its value.
A static variable has one value for the duration of the program. After one static function changes it, another static function reads the updated value.
#include <stdio.h>
static int score = 0;
static void add_score(int points) {
score += points;
}
static int get_score(void) {
return score;
}
int main(void) {
add_score(10);
add_score(5);
printf("%d\n", get_score());
return 0;
}Output:
15Use a file-scope static variable only for state that genuinely belongs to the module. Prefer focused functions for updates instead of assigning to it from arbitrary locations.
KNOWLEDGE QUIZ
Maintain a module scoreboard
Use a file-scope static score and compare it with a shadowing local parameter.
- Create static int score = 0.
- Update the shared score in add_points().
- Show that the preview_message(score) parameter does not modify the shared value.