0
0
C++programming~20 mins

Scope of variables in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Scope Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of variable shadowing in nested blocks

What is the output of the following C++ code?

C++
#include <iostream>

int main() {
    int x = 5;
    {
        int x = 10;
        std::cout << x << std::endl;
    }
    std::cout << x << std::endl;
    return 0;
}
A10\n5\n
B5\n10\n
C10\n10\n
D5\n5\n
Attempts:
2 left
💡 Hint

Remember that inner blocks can have variables with the same name that hide outer variables.

Predict Output
intermediate
2:00remaining
Output when modifying a global variable inside a function

What is the output of this C++ program?

C++
#include <iostream>

int count = 0;

void increment() {
    count += 1;
}

int main() {
    increment();
    increment();
    std::cout << count << std::endl;
    return 0;
}
A
2
B
0
C
1
D
Compilation error
Attempts:
2 left
💡 Hint

Global variables can be accessed and modified inside functions unless shadowed.

🔧 Debug
advanced
2:00remaining
Identify the error caused by variable scope

What error does this code produce when compiled?

C++
#include <iostream>

int main() {
    if (true) {
        int a = 10;
    }
    std::cout << a << std::endl;
    return 0;
}
AOutput: 10
BRuntime error: segmentation fault
CCompilation error: 'a' was not declared in this scope
DCompilation error: redefinition of 'a'
Attempts:
2 left
💡 Hint

Variables declared inside a block are not visible outside that block.

Predict Output
advanced
2:00remaining
Output of static variable inside a function

What is the output of this program?

C++
#include <iostream>

void counter() {
    static int count = 0;
    count++;
    std::cout << count << std::endl;
}

int main() {
    counter();
    counter();
    counter();
    return 0;
}
A
Compilation error
B
0
1
2
C
1
1
1
D
1
2
3
Attempts:
2 left
💡 Hint

Static variables inside functions keep their value between calls.

🧠 Conceptual
expert
3:00remaining
Understanding variable scope and lifetime in nested functions

Consider the following C++ code using lambda functions. What is the output?

C++
#include <iostream>
#include <functional>

int main() {
    int x = 5;
    auto f = [x]() mutable {
        x += 10;
        std::cout << x << std::endl;
    };
    f();
    f();
    std::cout << x << std::endl;
    return 0;
}
A
15
15
5
B
15
25
5
C
15
25
25
D
Compilation error
Attempts:
2 left
💡 Hint

Mutable lambdas capture variables by value but allow modification of the copy inside the lambda.