bool bSwitch = true;
double dSum = 1 + bSwitch?1:2;
因此, “DSUM” 是:你对这个C++表达式有什么期望?
A)= 1个
B)= 2
C)= 3
结果是公正荒谬和我撞坏一...
我使用VS2008 - > “微软(R)32位C/C++ - Optimierungscompiler版本15.00.21022.08献给80x86的”
bool bSwitch = true;
double dSum = 1 + bSwitch?1:2;
因此, “DSUM” 是:你对这个C++表达式有什么期望?
A)= 1个
B)= 2
C)= 3
结果是公正荒谬和我撞坏一...
我使用VS2008 - > “微软(R)32位C/C++ - Optimierungscompiler版本15.00.21022.08献给80x86的”
Spasibo Kiril! Ja ponjal 4to oblagalsja ;-) – maxw
这是一个优先的事情是吧。
bool bSwitch = true;
double dSum = (1 + bSwitch)?1:2;
dSum
为1.0
本来就容易与各地运营商明智的间距被发现。
我期望1.
,因为+
运算符优先于三元运算符。所以表达式被读取为
double dSum = (1 + bSwitch) ? 1:2;
和1 + bSwitch
是非零的,因此它的计算结果为true
。
警告,很明显,但我用的是真正的编译器:
void foo() {
bool bSwitch = true;
double dSum = 1 + bSwitch?1:2;
}
给出:
$ clang++ -fsyntax-only test.cpp
test.cpp:3:28: warning: operator '?:' has lower precedence than '+'; '+' will be evaluated first [-Wparentheses]
double dSum = 1 + bSwitch?1:2;
~~~~~~~~~~~^
test.cpp:3:28: note: place parentheses around the '+' expression to silence this warning
double dSum = 1 + bSwitch?1:2;
^
( )
test.cpp:3:28: note: place parentheses around the '?:' expression to evaluate it first
double dSum = 1 + bSwitch?1:2;
^
( )
1 warning generated.
是的,我给了EN整个命令行,它在默认情况下是在。
为了记录,每个C++编译器都会这样做。经验法则:加法和减法之前的乘法和除法;其他一切都会得到parens。 –
注意自己:在处理三元运算符时尽可能多地使用括号。 –