0
0
C++programming~20 mins

Variable declaration and initialization in C++ - Practice Problems & Coding Challenges

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

What is the output of this C++ code?

C++
#include <iostream>
int main() {
    int x;
    std::cout << x << std::endl;
    return 0;
}
AGarbage value (undefined behavior)
B1
CCompilation error
D0
Attempts:
2 left
💡 Hint

Local variables without initialization contain whatever was in memory before.

Predict Output
intermediate
2:00remaining
Value of initialized variable with brace syntax

What is the output of this code snippet?

C++
#include <iostream>
int main() {
    int a{5};
    std::cout << a << std::endl;
    return 0;
}
A0
B5
CCompilation error
DGarbage value
Attempts:
2 left
💡 Hint

Brace initialization sets the variable to the given value.

Predict Output
advanced
2:00remaining
Output of const variable initialization

What will this program print?

C++
#include <iostream>
int main() {
    const int x = 10;
    // x = 20; // Uncommenting this line causes error
    std::cout << x << std::endl;
    return 0;
}
ACompilation error
B20
CUndefined behavior
D10
Attempts:
2 left
💡 Hint

Const variables cannot be changed after initialization.

Predict Output
advanced
2:00remaining
Output of auto type deduction with initialization

What is the output of this code?

C++
#include <iostream>
#include <typeinfo>
int main() {
    auto val = 3.14;
    std::cout << typeid(val).name() << std::endl;
    return 0;
}
Af
Bi
Cd
Dc
Attempts:
2 left
💡 Hint

auto deduces the type from the initializer.

🧠 Conceptual
expert
3:00remaining
Behavior of static variable initialization

Consider this code snippet. What is the output after running main() twice?

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

int main() {
    func();
    func();
    return 0;
}
A1 2
B0 1
C1 1
D2 3
Attempts:
2 left
💡 Hint

Static variables keep their value between function calls.