Why does any combination of true and false return the value it does?
There is no combination of any boolean here. This ?:
operator returns first or second expression, not the condition itself.
condition ? first_expression : second_expression;
The condition must evaluate to true or false. If condition is true,
first_expression is evaluated and becomes the result. If condition is
false, second_expression is evaluated and becomes the result.
Since this operator is right-associative, your code works as;
true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7
evaluated as;
true ? false ? false ? (false ? 3 : 4) : 5 : 6 : 7
which evaluated as;
true ? false ? false ? 4 : 5 : 6 : 7
which evaluated as;
true ? false ? (false ? 4 : 5) : 6 : 7
which evaluated as;
true ? false ? 5 : 6 : 7
which evaluated as;
true ? (false ? 5 : 6) : 7
which evaluated as;
true ? 6 : 7
which returns 6
.
2
solved Multiple ternary operators and evaluating int as boolean mystery [closed]