So I was just trying some bit manipulation in C++. Here is what I tried:
int a = 1<<2;
cout<<a;
This gives the output as 4
.
int a = 1<<3;
cout<<a;
This gives the output as 8
But when I do:
int a = 1<<2 + 1<<3;
cout<<a;
It gives the output as 64
. Why so?
I also tried:
int a = 1<<2;
int b = 1<<3;
cout<<a + b;
Which gives the output as 12
as expected.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With