4
  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"

2
  • 2
    For the record, every C++ compiler will do the same. A rule of thumb: multiplication and division before addition and subtraction; everything else gets parens. Aug 30, 2012 at 8:39
  • 1
    Note to self: use as many parentheses as you can when dealing with the ternary operator. Aug 30, 2012 at 8:40

4 Answers 4

7

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

So, this is equivalent to

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

Thus, you have dSum == 1.

1
  • 1
    Spasibo Kiril! Ja ponjal 4to oblagalsja ;-)
    – maxw
    Aug 30, 2012 at 9:12
3

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.

0
3

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.