# precedence questions

• 10-01-2011
elpedoloco
precedence questions
true ? 1 : 2 + 3 // why is this 1? False = 0, true = 1 right? // Then why is this 1 .
also
24 / 6 * 2 // I got this as well.
has value 8, not value 2; likewise, the weird-looking expression
true ? false : true ? false : true // how? I don't understand the if true then false? false true?
• 10-01-2011
laserlight
Quote:

Originally Posted by elpedoloco
true ? 1 : 2 + 3 // why is this 1? False = 0, true = 1 right? // Then why is this 1 .

Uh, what did you think the result should be, and why?

Quote:

Originally Posted by elpedoloco
24 / 6 * 2 // I got this as well.
has value 8, not value 2; likewise, the weird-looking expression

24 / 6 == 4
4 * 2 == 8

Quote:

Originally Posted by elpedoloco
true ? false : true ? false : true // how? I don't understand the if true then false? false true?

That is okay, I don't understand it either because I do not remember offhand what are the rules, even though I checked not too long ago. I could check again, but code like this is just badly written. If parentheses were used for grouping, it would be better, but even then the use of nested conditional operator expressions is bad practice.
• 10-01-2011
rags_to_riches
As to the math one, read this page on precedence. Note that multiplication and division are at the same precedence level, so we go to the third column for associativity and notice it's left-to-right, so the expression is evaluated as Laserlight described.
• 10-01-2011
Shingetsu Kurai
The rules are as follows
Code:

`type variable = condition ? a : b`
a will return if the condition returns true
b will return if it is false

example:

Code:

`int never_true = 5>6 ? 999 : 10;`
never_true will ALWAYS be 10.
• 10-01-2011
grumpy
Quote:

Originally Posted by elpedoloco
true ? 1 : 2 + 3 // why is this 1? False = 0, true = 1 right? // Then why is this 1 .

In C, zero is false, and anything else is true. The ?: operator has lower precedence than addition, so true ? 1 : 2 + 3 is equal to true ? 1 : (2+3).

Others have already explained the ?: operator, so I'll leave this example at that.
Quote:

Originally Posted by elpedoloco
24 / 6 * 2 // I got this as well.
has value 8, not value 2;

Primary school arithmetic is applicable here, and if you don't understand primary school arithmetic then you should be ashamed (unless you are about five years old).

Multiplication and division have the same precedence so, if more than one is in an expression, they are done left to right. 24/6*2 is equal to (24/6)*2.

I'll leave your last example alone. You can nut it out based on explanations others have already given of the :? operator.