6.4 — Where variables live (scope)

📘 Chapter 6⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Local variables#

A variable made inside a function (or any { } block) only exists inside that block. This is called its scope.

C++ — wrong ✗
void test(){    int secret { 42 };} int main(){    test();    std::cout << secret;   // error: secret does not exist here    return 0;}

When the block ends, the variable is destroyed.

Key idea

Each function has its own private variables. Two functions can both have a variable called x, and they won't affect each other.

Blocks inside blocks#

C++ — wrong ✗
int main(){    int a { 1 };    {        int b { 2 };        std::cout << a + b;   // fine: both visible here    }    std::cout << b;   // error: b is gone    return 0;}

Global variables#

A variable made outside of all functions is global. Every function can see and change it.

C++
int score { 0 };   // global void addPoint(){    ++score;}
Good habit

Avoid global variables (except constants). When any code anywhere can change a value, bugs become very hard to find. Pass values in and return them out instead.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.