Operator precedence is all about solving ambiguities. Let's say for example we have two operators op1 and op2 and the following expression:
x = a op1 b op2 c
We could resolve this logically as
tmp = a op1 b
x = tmp op2 c
But it would also be possible to evaluate op2 first, like so:
tmp = b op2 c
x = a op1 tmp
This is ambigous. To solve the ambiguity we could either demand parentheses or have to give one of the operators higher precedence. This is basically the same what we use in mathematics with an expression like 1 + 2 * 3 where the multiplication has higher precedence and has to be calculated first.
Wat does that mean for your example? As you've already written, || has a higher precedence than ?:. This means that
true || false
will be evaluated first and always results in true. So your ternary effectively becomes
true ? false : true
and will always result in false.
How does the compiler reach that decision? Let's have a (simplified) look at the steps:
- initially the compiler sees
true which is already a value.
- the compiler sees
|| an knows now that there has to follow another value or evaluated expression.
- the compiler then sees
false. This would be a value but since it could be part of another expression it's not done yet.
- next, the compiler encounters
? which it identifies this as the ternary operator
- since the ternary has a lower precedence than
|| it has to treat the entire expression true || false as the first operand of the ternary.
As to why the ternary operator has a lower precedence than || I can only speculate that it is for consistency. The ternary is not only the only operator with three operands but also only the second and the third need to have the same datatype whereas the first is always a bool. The lower precedence ensures that these two assignments are semantically the same:
bool b = condition1 || condition2 ? true : false;
int i = condition1 || condition2 ? 23 : 42;
||is short-circuit. If the first operand evaluates totrue, the rest will be ignored. - imsmntrueortrue || false. - GSerg