条件运算符“?:”在 C++
为什么这个说法 :
int a = 7, b = 8, c = 0;
c = b > a? a > b? a++: b++: a++ ? b++:a--;
cout << c;
不等于 :
int a = 7, b = 8, c = 0;
c = (b > a? (a > b? a++: b++): a++)? b++: a--;
cout << c;
且等于 :
int a = 7, b = 8, c = 0;
c = b > a? (a > b? a++: b++): (a++? b++: a--);
cout << c;
请给我一些理由。为什么 ?
Why this statement :
int a = 7, b = 8, c = 0;
c = b > a? a > b? a++: b++: a++ ? b++:a--;
cout << c;
is not equal to :
int a = 7, b = 8, c = 0;
c = (b > a? (a > b? a++: b++): a++)? b++: a--;
cout << c;
and is equal to :
int a = 7, b = 8, c = 0;
c = b > a? (a > b? a++: b++): (a++? b++: a--);
cout << c;
Please give me some reason. Why ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
运算符优先级和关联性
运算符优先级和关联性表C++
Operator precedence and associativity
Table of operator precedence and associativity for C++
只需将其放在多行中即可查看差异:
不等于:
并且等于:
Just put it on multiple lines to see the differences :
is not equal to :
and is equal to :
另外,请注意,这些(可怕的)表达式仅是确定性的,因为使用了 ?: 运算符。该运算符是 C 语言中实际指定求值顺序的极少数运算符之一。如果您编写了一些其他令人讨厌的内容,例如
i++ + ++i;
,那么编译器可能会首先计算左操作数或右操作数,它选择的操作数在 C 语言中没有定义。根据经验,切勿将 ++ 运算符与其他运算符一起用作表达式的一部分。仅在其自己的行上使用它(或作为循环迭代器)。因为,与主流观点相反,实际上没有理由将它与其他运算符一起使用。
Also, please note that these (horrible) expressions are deterministic only because the ?: operator is used. This operator is one of the very few operators in the C language where the order of evaluation is actually specified. Had you written some other abomination like
i++ + ++i;
then the compiler could have evaluated the left operand or the right operand first, which it picks is not defined in the C language.As a rule of thumb, never use the ++ operator as part of an expression with other operators. Only use it on a line of its own (or as loop iterator). Because, against mainstream belief, there is actually never a reason to use it together with other operators.