1 << 1 evaluates to 2. The << operator shifts the bits of the number 1 one place to the left. In binary, 0001 moves up one place and becomes 0010, which is 2. The shift does not change the 1 itself. It produces a new value.
Step by step in binary
| Step | Bit pattern | Value |
|---|---|---|
| Start: the number 1 | 0001 |
1 |
| Shift left one place | 0010 |
2 |
The zero fills the empty place on the right, and the bit that was at position 0 moves to position 1. An int has more bits than four, but the extra bits at the top are all zero, so the pattern works the same way.
Same as multiplying by 2
For a non-negative value that does not overflow, x << 1 gives the same result as x * 2. So 1 << 1 matches 1 * 2, and 3 << 1 gives 6. The shift is a bit operation, while * expresses arithmetic, so * is clearer when you mean multiplication.
A program that prints it
#include <stdio.h>
int main(void) {
int a = 1;
printf("1 << 1 = %d\n", 1 << 1);
printf("a << 1 = %d\n", a << 1);
printf("a after the shift = %d\n", a);
return 0;
}
Output:
1 << 1 = 2
a << 1 = 2
a after the shift = 1
The variable a is still 1 after the shift. The shifted value exists only in the expression that uses it.
Watch the precedence
The shift has lower precedence than +, so 1 << 1 + 1 is read as 1 << (1 + 1), which is 4. The arithmetic operators bind more tightly than the shift. Many compilers warn about this when warnings are turned on. To shift first and then add 1, use parentheses: (1 << 1) + 1 is 3.
Printing it in C++ streams
In C++, the << used with std::cout is stream insertion, not a shift. Because of that, std::cout << 1 << 1 prints 11. To print the shifted value, put it in parentheses.
#include <iostream>
int main() {
std::cout << 1 << 1 << "\n"; // prints 11
std::cout << (1 << 1) << "\n"; // prints 2
return 0;
}