What is the output of the following C++ code?
#include <iostream> int main() { int x = 5; { int x = 10; std::cout << x << std::endl; } std::cout << x << std::endl; return 0; }
Remember that inner blocks can have variables with the same name that hide outer variables.
The inner block declares a new variable x with value 10, which shadows the outer x. So inside the block, x is 10. Outside, it remains 5.
What is the output of this C++ program?
#include <iostream> int count = 0; void increment() { count += 1; } int main() { increment(); increment(); std::cout << count << std::endl; return 0; }
Global variables can be accessed and modified inside functions unless shadowed.
The global variable count starts at 0. Each call to increment() adds 1. After two calls, count is 2.
What error does this code produce when compiled?
#include <iostream> int main() { if (true) { int a = 10; } std::cout << a << std::endl; return 0; }
Variables declared inside a block are not visible outside that block.
The variable a is declared inside the if block and is not accessible outside. Trying to use it outside causes a compilation error.
What is the output of this program?
#include <iostream> void counter() { static int count = 0; count++; std::cout << count << std::endl; } int main() { counter(); counter(); counter(); return 0; }
Static variables inside functions keep their value between calls.
The static variable count is initialized once to 0, then incremented each call. So outputs 1, 2, 3.
Consider the following C++ code using lambda functions. What is the output?
#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; }
Mutable lambdas capture variables by value but allow modification of the copy inside the lambda.
The lambda captures x by value, so it works on a copy stored in the lambda object. The mutable keyword allows modifying that copy, which persists across calls, outputting 15 then 25. The original x outside remains 5.