What would you expect from this expression in C ++?

bool bSwitch = true; double dSum = 1 + bSwitch?1:2; 

So, "dSum":

a) = 1
b) = 2
c) = 3

The result is just ridiculous, and I got it for it ...

I am using VS2008 -> "Microsoft (R) 32-bit C / C ++ - Optimierungscompiler Version 15.00.21022.08 for 80x86"

+4
source share
4 answers

operator+ has a higher precedence than the ternary operator ?: .

So this is equivalent

 double dSum = ( 1 + bSwitch ) ? 1 : 2; 

So you have dSum == 1 .

+7
source

It is not important.

 bool bSwitch = true; double dSum = (1 + bSwitch)?1:2; 

dSum will be 1.0

It would be easier to find a reasonable distance around the operators.

+3
source

I would expect 1. because the + operator takes precedence over the ternary operator. So the expression reads like

 double dSum = (1 + bSwitch) ? 1:2; 

and 1 + bSwitch is nonzero, so it evaluates to true .

See operator priority .

+3
source

The warning is obvious, but I'm using a real compiler:

 void foo() { bool bSwitch = true; double dSum = 1 + bSwitch?1:2; } 

gives:

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

And yes, I gave it all over the command line, by default.

+1
source

All Articles