/** * @file scopes_annotated.cpp * @author Jeffrey Bergamini for CS 19 Boot Camp, jeffrey.bergamini@cabrillo.edu * * Let's add *memory addresses* to the output to see which symbol `x` represents in which context. */ #include int x; // global variable, global scope void f1() { x = 2; // assigns to global variable `x` std::cout << &x << '\t' << x << '\n'; } void f2(int x) { std::cout << &x << '\t' << x << '\n'; { int x; // local variable (local to function `f1()`), scoped within anonymous block x = 4; // assigns to local variable `x` scoped within anonymous block std::cout << &x << '\t' << x << '\n'; } x = 5; // assigns to local variable `x` (function parameter) std::cout << &x << '\t' << x << '\n'; } int main() { x = 1; // assigns to global variable (i.e., global var `x` is a *lvalue*) std::cout << &x << '\t' << x << '\n'; f1(); std::cout << &x << '\t' << x << '\n'; // function `f1()` should have mutated global variable `x` f2(3); std::cout << &x << '\t' << x << '\n'; // function `f2()` has not mutated global variable `x` int x; // local variable, local scope x = 6; // assigns to local variable `x` (global `x` is now "shadowed" for the rest of the block) std::cout << &x << '\t' << x << '\n'; }