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 <iostream>
using namespace std;
void swap(int a, int b) {
int temporary = a;
a = b;
b = temporary;
cout << "inside swap(): " << a << ' ' << b << endl;
}
int main() {
int a = 1;
int b = 2;
cout << "Before: " << a << ' ' << b << endl;
swap(a, b);
cout << "After: " << a << ' ' << b << endl;
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 <iostream>
using namespace std;
static int score = 0;
static void add_score(int points) {
score += points;
}
static int get_score() {
return score;
}
int main() {
add_score(10);
add_score(5);
cout << get_score() << endl;
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.