Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird output when summing 1<<2 and 1<<3 in C++

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.

like image 554
Divyansh Avatar asked Oct 12 '19 13:10

Divyansh


3 Answers

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.

like image 58
Drew McGowen Avatar answered Oct 20 '22 20:10

Drew McGowen


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"

like image 37
phuclv Avatar answered Oct 20 '22 20:10

phuclv


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);
like image 43
sephiroth Avatar answered Oct 20 '22 20:10

sephiroth