What is the output of the following C++ code?
Fujitsu technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the output of the following C++ code?
#include <iostream>
int main() {
int x = 5;
std::cout << (x << 1) << std::endl;
return 0;
}
Show answer & explanation
The bitwise left shift operator (<<) shifts the bits of the operand to the left by the specified number of positions, which is mathematically equivalent to multiplying the integer by 2 raised to the power of the shift amount.
Step-by-step Derivation:
Step 1: Identify the initial value of x. x = 5.
Step 2: Convert the decimal value 5 to its binary representation. 5 in binary is 00000101 (assuming an 8-bit representation for simplicity).
Step 3: Apply the left shift operation (x << 1). This moves all bits one position to the left and fills the vacant rightmost position with a 0.
Step 4: Binary 00000101 shifted left by 1 becomes 00001010.
Step 5: Convert the resulting binary 00001010 back to decimal. (1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (0 * 2^0) = 8 + 0 + 2 + 0 = 10.
Step 6: The output of std::cout << (x << 1) is therefore 10.