三元运算符的右结合性

编程入门 行业动态 更新时间:2024-10-27 10:25:10
本文介绍了三元运算符的右结合性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 std::cout << (true ? "high pass" : false ? "fail" : "pass")

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

更多推荐

三元运算符的右结合性

本文发布于:2023-11-07 22:23:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567598.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!