Right Associativity of Ternary Operator

五迷三道 提交于 2021-02-04 08:40:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!