What is the output of this C++ code?
#include <iostream> int main() { int x; std::cout << x << std::endl; return 0; }
Local variables without initialization contain whatever was in memory before.
Local variables in C++ are not automatically initialized. Printing an uninitialized int gives an unpredictable value (garbage).
What is the output of this code snippet?
#include <iostream> int main() { int a{5}; std::cout << a << std::endl; return 0; }
Brace initialization sets the variable to the given value.
Using brace initialization int a{5}; sets a to 5.
What will this program print?
#include <iostream> int main() { const int x = 10; // x = 20; // Uncommenting this line causes error std::cout << x << std::endl; return 0; }
Const variables cannot be changed after initialization.
The const int x is initialized to 10 and cannot be changed. The program prints 10.
What is the output of this code?
#include <iostream> #include <typeinfo> int main() { auto val = 3.14; std::cout << typeid(val).name() << std::endl; return 0; }
auto deduces the type from the initializer.
auto val = 3.14; deduces val as double. typeid(val).name() returns 'd' for double on most compilers.
Consider this code snippet. What is the output after running main() twice?
#includevoid func() { static int count = 0; count++; std::cout << count << std::endl; } int main() { func(); func(); return 0; }
Static variables keep their value between function calls.
The static variable count starts at 0, increments each call. First call prints 1, second prints 2.