Bird
Raised Fist0
C++programming~10 mins

Scope of variables in C++ - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Scope of variables
Start Program
↓
Declare Global Variable
↓
Enter main()
↓
Declare Local Variable
↓
Use Variables
↓
Enter Block (if/for)
↓
Declare Block Variable
↓
Use Variables in Block
↓
Exit Block
↓
Use Variables in main()
↓
End Program
This flow shows how variables declared in different places have different visibility and lifetime during program execution.
Execution Sample
C++
int x = 10; // global

int main() {
  int x = 20; // local
  if (true) {
    int x = 30; // block
    // print x
  }
  // print x
}
This code shows three variables named x in different scopes: global, local in main, and block inside if.
Execution Table
StepScopeVariable x ValueActionOutput
1Global10Declare global x=10
2main() local20Declare local x=20
3if block30Declare block x=30
4if block30Print x inside block30
5Exit block20Block x destroyed, back to main local x
6main() local20Print x inside main20
7End10Global x still exists but not used here
💡 Program ends after main() finishes; block variable x is destroyed after block ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
Global x1010101010
main() local xN/A20202020
block xN/AN/A30N/AN/A
Key Moments - 3 Insights
Why does the print inside the block show 30, not 20 or 10?
Because inside the block, the block variable x=30 shadows the local and global x. See execution_table step 4.
After the block ends, which x is used when printing?
The block variable x is destroyed after the block ends, so the local x=20 in main() is used again. See execution_table step 6.
Is the global x accessible inside main()?
Yes, but it is shadowed by the local x=20, so using x refers to the local one inside main(). See variable_tracker for values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x printed inside the if block (step 4)?
A20
B30
C10
DUndefined
💡 Hint
Check execution_table row with step 4 under 'Output' column.
At which step does the block variable x get destroyed?
AStep 5
BStep 3
CStep 6
DStep 7
💡 Hint
Look at execution_table step 5 description about exiting the block.
If we remove the local x=20 in main(), what value would be printed at step 6?
A30
B20
C10
DError
💡 Hint
Without local x, main() uses global x=10. See variable_tracker for global x value.
Concept Snapshot
Scope of variables in C++:
- Global variables declared outside functions are accessible everywhere unless shadowed.
- Local variables declared inside functions hide global variables with same name.
- Block variables declared inside blocks (if, for) hide outer variables and exist only inside block.
- When block ends, block variables are destroyed and outer variables become visible again.
- Variable name resolution uses closest scope first.
Full Transcript
This visual execution shows how variables named x declared in different scopes behave in C++. The global x=10 exists throughout the program. Inside main(), a local x=20 hides the global x. Inside the if block, a block x=30 hides both local and global x. Printing inside the block shows 30. After the block ends, the block x is destroyed, so printing in main() shows 20. The global x remains but is shadowed by local variables. This demonstrates variable scope and shadowing clearly.

Practice

(1/5)
1. What is the scope of a variable declared inside a function in C++?
easy
A. It can only be used inside that function.
B. It can be used anywhere in the program.
C. It can be used only in the main function.
D. It can be used in all functions after declaration.

Solution

  1. Step 1: Understand local variable scope

    A variable declared inside a function is local to that function only.
  2. Step 2: Check usage outside the function

    Such variables cannot be accessed outside their function block.
  3. Final Answer:

    It can only be used inside that function. -> Option A
  4. Quick Check:

    Local variable scope = inside function only [OK]
Hint: Local variables live only inside their function block [OK]
Common Mistakes:
  • Thinking local variables are accessible globally
  • Confusing local and global variable scopes
2. Which of the following is the correct way to declare a global variable in C++?
easy
A. int x; inside main() function
B. int x; outside all functions
C. int x; inside a block { }
D. int x; inside a for loop

Solution

  1. Step 1: Identify global variable declaration

    Global variables must be declared outside all functions and blocks.
  2. Step 2: Check each option

    Only int x; outside all functions declares the variable outside all functions, making it global.
  3. Final Answer:

    int x; outside all functions -> Option B
  4. Quick Check:

    Global variable declared outside functions [OK]
Hint: Global variables declared outside all functions [OK]
Common Mistakes:
  • Declaring global variables inside functions
  • Declaring variables inside loops thinking they are global
3. What will be the output of the following C++ code?
int x = 5;
void func() {
    int x = 10;
    std::cout << x << std::endl;
}
int main() {
    func();
    std::cout << x << std::endl;
    return 0;
}
medium
A. 10\n5
B. 10\n10
C. 5\n5
D. 5\n10

Solution

  1. Step 1: Analyze variable shadowing in func()

    Inside func(), local x = 10 shadows global x = 5, so prints 10.
  2. Step 2: Analyze main() output

    After func(), main() prints global x = 5.
  3. Final Answer:

    10\n5 -> Option A
  4. Quick Check:

    Local shadows global, prints 10 then 5 [OK]
Hint: Local variable shadows global inside function [OK]
Common Mistakes:
  • Assuming global x changes inside func()
  • Confusing which x is printed in main()
4. Identify the error in the following C++ code:
int main() {
    std::cout << x << std::endl;
    int x = 5;
    return 0;
}
medium
A. Error: x declared twice
B. No error, prints 5
C. Error: Missing semicolon
D. Error: x used before declaration

Solution

  1. Step 1: Check variable usage before declaration

    The code tries to print x before it is declared.
  2. Step 2: Understand C++ variable initialization rules

    Variables must be declared before use; using x before declaration causes error.
  3. Final Answer:

    Error: x used before declaration -> Option D
  4. Quick Check:

    Use after declaration required [OK]
Hint: Declare variables before using them [OK]
Common Mistakes:
  • Assuming declaration order does not matter
  • Ignoring compiler errors about undeclared variables
5. Consider the following code snippet:
int x = 1;
void update() {
    x = 5;
    int x = 10;
    std::cout << x << std::endl;
}
int main() {
    update();
    std::cout << x << std::endl;
    return 0;
}

What will be the output and why?
hard
A. 10\n5 because local x shadows global, but global x updated before local declaration
B. 10\n1 because global x not updated due to local shadowing
C. Compilation error due to variable redeclaration
D. 5\n10 because global x updated first, then local x printed

Solution

  1. Step 1: Analyze variable declaration order

    The line x = 5; appears before the local variable x is declared in the same function.
  2. Step 2: Understand C++ rules on variable usage

    Using a variable before its local declaration in the same scope is illegal and causes a compilation error.
  3. Step 3: Reason about the error

    Because local x is declared after x = 5;, the assignment tries to assign to local x before its declaration, which is invalid.
  4. Final Answer:

    Compilation error due to variable redeclaration -> Option C
  5. Quick Check:

    Using variable before declaration in same scope causes error [OK]
Hint: Cannot use variable before local declaration in same scope [OK]
Common Mistakes:
  • Thinking there's a compilation error on x=5
  • Believing local shadowing prevents global update before declaration
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard