问题
std::cout << (true ? "high pass" : false ? "fail" : "pass")
is the same as
std::cout << (true ? "high pass" : (false ? "fail" : "pass"))
Since the ternary operator is right associative, why don't we perform the right-hand operation first? Shouldn't pass
be printed instead of high pass
?
回答1:
You misunderstood operator associativity. It's simply the way to group operators with the same precedence and doesn't affect order of evaluation in any way. So cond1 ? 1 : cond2 ? 2 : cond3 ? 3 : 4
will be parsed as
cond1 ? 1 : (cond2 ? 2 : (cond3 ? 3 : 4))
from the right and not as
((cond1 ? 1 : cond2) ? 2 : cond3) ? 3 : 4
which groups operands from the left. Once parentheses are added then the expression will be evaluated in its normal order
In fact PHP made the ternary operator left-associative which is one of its biggest mistake and it's unfixable by now
回答2:
The Ternary Operator works like
variable = (condition) ? expressionTrue : expressionFalse;
This could be expressed like
if (condition)
{
expressionTrue;
}
else
{
expressionFalse;
}
The condition of both of your statements statements is true, so the expressionTrue will be always executed. There is no reason to check the expressionFalse in a statement like
std::cout << (true ? "high pass" : (false ? "fail" : "pass"))
来源:https://stackoverflow.com/questions/65627247/right-associativity-of-ternary-operator