与
std::cout << (true ? "high pass" : (false ? "fail" : "pass"))既然三元运算符是右结合的,为什么不先进行右手操作呢?不应该打印 pass 而不是 high 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?
推荐答案你误解了 operator associativity.这只是将具有相同优先级的运算符分组的方法,并且不会'不会以任何方式影响评估顺序.那么 cond1 ?1:条件2?2:条件3?3 : 4 将被解析为
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))从右边而不是像
((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
事实上 PHP 使三元运算符左结合最大的错误,现在无法修复
In fact PHP made the ternary operator left-associative which is one of its biggest mistake and it's unfixable by now
更多推荐
三元运算符的右结合性
发布评论