Postfix/Prefix运算符的优先级和关联性 [英] Postfix/Prefix operator precedence and associativity

查看:115
本文介绍了Postfix/Prefix运算符的优先级和关联性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对后缀/前缀运算符的优先级关联性感到困惑.

I'm confused about the precedence and associativity of postfix/prefix operators.

一方面,在我阅读K& R书时,它指出:

On one hand, as I'm reading K&R book, it states that:

(* ip)++

(*ip)++

在最后一个示例中,括号是必需的;没有它们,表达式将使ip而不是它指向的值增加,因为*和++等一元运算符从右到左关联.

The parentheses are necessary in this last example; without them, the expression would increment ip instead of what it points to, because unary operators like * and ++ associate right to left.

更不用说后缀/前缀运算符之间的关联性差异了.两者均一视同仁.该书还指出*和++具有相同的优先级.

No mention whatsoever of a difference of associativity between postfix/prefix operators. Both are treated equally. The book also states that * and ++ have the same precedence.

另一方面,此页面指出:

1)前缀++和*的优先级相同.两者的关联性是从右到左.

1) Precedence of prefix ++ and * is same. Associativity of both is right to left.

2)后缀++的优先级高于*和前缀++.后缀++的关联性从左到右.

2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.

我应该信任哪个人?这些年来,随着C版本的改变,情况有所改变吗?

Which one should I trust? Is it something that changed with the C revisions over the years?

推荐答案

您可以参考 C11标准,尽管它关于优先级的章节有些难以理解.参见秒. 6.5.1. (脚注85表示".该语法指定了运算符在表达式求值中的优先级,这是相同的 作为该小节中各主要小节的顺序,则优先级最高." )

You can refer to the C11 standard although its section on precedence is a little hard to follow. See sec. 6.5.1. (footnote 85 says "The syntax specifies the precedence of operators in the evaluation of an expression, which is the same as the order of the major subclauses of this subclause, highest precedence first.")

基本上,后缀运算符的优先级高于前缀,因为后缀运算符在该节中早于6.5.2.4与6.5.3.1.因此,K& R是正确的(这并不奇怪!),*ip++表示*(ip++),与(*ip)++不同,但是我说的是由于关联性,这有点误导.而且geeksforgeeks网站的第2点也是正确的.

Basically, postfix operators are higher precedence than prefix because they come earlier in that section, 6.5.2.4 vs. 6.5.3.1. So K&R is correct (no surprise there!) that *ip++ means *(ip++), which is different from (*ip)++, however its point about it being due to associativity is a bit misleading I'd say. And the geeksforgeeks site's point #2 is also correct.

这篇关于Postfix/Prefix运算符的优先级和关联性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆