maxw
maxw

Reputation: 123

What would you expect of this C++ expression?

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

So "dSum" is:

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

The result is just rediculous and i got bashed for it...

I'm using VS2008 -> "Microsoft (R) 32-Bit C/C++-Optimierungscompiler Version 15.00.21022.08 für 80x86"

Upvotes: 4

Views: 285

Answers (4)

Matthieu M.
Matthieu M.

Reputation: 299930

A warning, obviously, but I use a true 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 en entire command line, it's on by default.

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38173

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

So, this is equivalent to

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

Thus, you have dSum == 1.

Upvotes: 7

juanchopanza
juanchopanza

Reputation: 227418

I would expect 1., because the + operator takes precedence over the ternary operator. So the expression is read as

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

and 1 + bSwitch is non-zero, so it evaluates as true.

See operator precedence.

Upvotes: 3

john
john

Reputation: 8027

It's a precedence thing isn't it.

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

dSum will be 1.0

Would have been easier to spot with sensible spacing around the operators.

Upvotes: 3

Related Questions