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

强颜欢笑 提交于 2019-12-23 08:39:08

问题


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.


回答1:


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.




回答2:


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"




回答3:


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);


来源:https://stackoverflow.com/questions/58354730/weird-output-when-summing-12-and-13-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!