输出流中的C ++运算符优先级 [英] C++ operator precedence in output stream

查看:64
本文介绍了输出流中的C ++运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

c 的计算结果为 0 ,因为 * + 运算符的运算符优先级高于 == ,其结果是 c 本质上计算为(a * b + b)== 0 ,这是错误的.

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.

为什么将相同的表达式放在 cout 语句输出4中?

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

推荐答案

因为优先级这些运算符是 operator * > operator + > operator<< > operator == .然后 cout<<a * b + b == 0; 等效于(cout<<((a * b)+ b))== 0; .

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

然后将打印出((a * b)+ b))的结果,即 4 ,然后返回(cout<<(((a * b)+ b)),即将 cout 0 进行比较.在C ++ 11之前,可以通过

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.

这篇关于输出流中的C ++运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆