C++ operator precedence in output stream

◇◆丶佛笑我妖孽 提交于 2020-11-30 02:08:08

问题


int a = 1, b = 2;
int c = a*b + b==0; // c = 0
cout << a*b + b==0; // outputs 4

c evaluates to 0 because the operator precedence of the * and + operators is higher than == as a result of which c essentially evaluates to (a*b+b)==0 which is false.

Why does putting the same expression in a cout statement output 4?


回答1:


Because the precedence of these operators are operator* > operator+ > operator<< > operator==. Then cout << a*b + b==0; is equivalent with (cout << ((a*b) + b)) == 0;.

Then the result of ((a*b) + b)), i.e. 4 will be printed out, then the returned value of (cout << ((a*b) + b)), i.e. cout is compared with 0. Before C++11 cout could be implicitly converted to void* via operator void*, which returns a null pointer when steram has any errors. So here it's compared with 0 (i.e. the null pointer), and does nothing further more with the result.




回答2:


The answr by @songyuanyao already explains the behavior of code.

I want to respond to the OP by saying that it will much better to write code that is easy to follow.

If you can't clearly see the logic of the expression, simplify it. Use parenthesis to make them easier to understand. Unless you are writing code for an obfuscated code contest, there is no excuse for writing such code.

Transform those line

int c = a*b + b==0; // c = 0

to

int c = (a*b) + (b==0);

or to

int c = ((a*b + b) == 0);

depending on your intention.



来源:https://stackoverflow.com/questions/41972953/c-operator-precedence-in-output-stream

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