Weird output when summing 1<<2 and 1<<3 in C++
This is because addition has a higher operator precedence than bitshift. In other words, your second example is equivalent to 1 << (2 + 1) << 3
Furthermore, since bitshifting is left-associative, it's the same as (1 << (2 + 1)) << 3
. This simplifies to 8 << 3
, which is 64
.
It's about operator precedence
+
has higher precedence than shift operators, therefore 1<<2 + 1<<3
is done as 1 << (2 + 1) << 3
which is similar to 1 << 6 == 64
(since <<
is left-associative, as you can see in the precedence table in the link above)
That's also why cout<<a + b;
works, because it's parsed as cout<<(a + b);
, otherwise you'll get some errors like "can't add a number to a stream"
The +
operator has a higher precedence than <<
operator, so here's that line is being evaluated:
int a = (1<<(2 + 1))<<3;
You should group it like this with parentheses:
int a = (1<<2) + (1<<3);