5.2 Scope and Storage
Scope describes where a name can be used. A variable declared inside a function is local to that function.
cpp
int add(int a, int b) {
int total = a + b;
return total;
}
int main() {
// total is not visible here
return 0;
}Parameters are also local variables. In C++, ordinary parameters are passed by value, which means the function receives copies of the arguments.
cpp
void change(int x) {
x = 100;
}
int main() {
int number = 5;
change(number);
std::cout << number << std::endl; // still 5
return 0;
}This is why a simple swap function does not change the caller's variables when the parameters are passed by value.
cpp
void swap_values(int a, int b) {
int temp = a;
a = b;
b = temp;
}To change a caller's variable directly, C++ commonly uses references. You will see them more later, but the shape is worth recognizing now.
cpp
void swap_values(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}A static local variable is initialized once and keeps its value between function calls.
cpp
void count_calls() {
static int count = 0;
count++;
std::cout << count << std::endl;
}Use local variables by default. They make programs easier to reason about because each function owns its temporary work.
Loading concept check...
Loading practice...