Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 218
maxw Avatar asked Dec 09 '22 21:12

maxw


2 Answers

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

So, this is equivalent to

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

Thus, you have dSum == 1.

like image 149
Kiril Kirov Avatar answered Dec 11 '22 10:12

Kiril Kirov


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.

like image 28
john Avatar answered Dec 11 '22 11:12

john