?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
下表列出了 C 運(yùn)算符的優(yōu)先級(jí)和關(guān)聯(lián)性。運(yùn)營(yíng)商從上到下排列,優(yōu)先級(jí)遞減。
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 | ++ -- | Suffix/postfix increment and decrement | Left-to-right |
() | Function call | ||
[] | Array subscripting | ||
. | Structure and union member access | ||
-> | Structure and union member access through pointer | ||
(type){list} | Compound literal(C99) | ||
2 | ++ -- | Prefix increment and decrement | Right-to-left |
| Unary plus and minus | ||
! ~ | Logical NOT and bitwise NOT | ||
(type) | Type cast | ||
* | Indirection (dereference) | ||
& | Address-of | ||
sizeof | Size-of | ||
_Alignof | Alignment requirement(C11) | ||
3 | * / % | Multiplication, division, and remainder | Left-to-right |
4 |
| Addition and subtraction | |
5 | << >> | Bitwise left shift and right shift | |
6 | < <= | For relational operators < and ≤ respectively | |
| For relational operators > and ≥ respectively | ||
7 | == != | For relational = and ≠ respectively | |
8 | & | Bitwise AND | |
9 | ^ | Bitwise XOR (exclusive or) | |
10 | | | Bitwise OR (inclusive or) | |
11 | && | Logical AND | |
12 | || | Logical OR | |
13note 1 | ?: | Ternary conditionalnote 2 | Right-to-Left |
14 | = | Simple assignment | |
+= -= | Assignment by sum and difference | ||
*= /= %= | Assignment by product, quotient, and remainder | ||
<<= >>= | Assignment by bitwise left shift and right shift | ||
&= ^= |= | Assignment by bitwise AND, XOR, and OR | ||
15 | , | Comma | Left-to-right |
虛構(gòu)的優(yōu)先級(jí)別,請(qǐng)參閱下面的注釋
條件運(yùn)算符中間的表達(dá)式(在?
和之間:
)被解析為括號(hào):它的優(yōu)先級(jí)相對(duì)于?:
被忽略。
解析表達(dá)式時(shí),某行上列出的運(yùn)算符將被綁定得比它下面一行中列出的任何運(yùn)算符更緊密(就像通過(guò)括號(hào)一樣)。例如,表達(dá)式*p++
被解析為*(p++)
,而不是(*p)++
。
位于同一單元格中的運(yùn)算符(單元格中列出的可能有多行運(yùn)算符)在給定方向上以相同的優(yōu)先級(jí)進(jìn)行評(píng)估。例如,表達(dá)式a=b=c
被解析為a=(b=c)
,而不是(a=b)=c
由于從右到左的關(guān)聯(lián)性。
優(yōu)先級(jí)和關(guān)聯(lián)性與評(píng)估順序無(wú)關(guān)。
Ct語(yǔ)言標(biāo)準(zhǔn)沒(méi)有指定運(yùn)算符優(yōu)先級(jí)。它指定語(yǔ)言語(yǔ)法,并從中派生優(yōu)先級(jí)表以簡(jiǎn)化理解。有一部分語(yǔ)法不能用優(yōu)先表來(lái)表示:賦值表達(dá)式不允許作為條件運(yùn)算符的右手操作數(shù),所以e = a < d ? a++ : a = d
是不能被解析的表達(dá)式,因此是條件和賦值的相對(duì)優(yōu)先級(jí)運(yùn)營(yíng)商不容易描述。
但是,許多 C 編譯器使用非標(biāo)準(zhǔn)表達(dá)式語(yǔ)法,其中?:
指定更高的優(yōu)先級(jí)=
,因?yàn)樗馕鲈摫磉_(dá)式e = ( ((a < d) ? (a++) : a) = d )
,然后由于語(yǔ)義限制而無(wú)法編譯:?:
從不是左值,并且=
需要在左邊有可修改的左值。這是在此頁(yè)面上呈現(xiàn)的表格。
請(qǐng)注意,這在 C ++中是不同的,其中條件運(yùn)算符具有與賦值相同的優(yōu)先級(jí)。
一元運(yùn)算符的關(guān)聯(lián)性規(guī)范是多余的,并且只顯示完整性:一元前綴運(yùn)算符總是從右到左(sizeof ++*p
是sizeof(++(*p))
)和一元后綴運(yùn)算符總是從左到右(a[1][2]++
是((a[1])[2])++
)相關(guān)聯(lián)。請(qǐng)注意,關(guān)聯(lián)性對(duì)于成員訪問(wèn)操作符是有意義的,即使它們與一元后綴操作符分組在一起:a.b++
被解析(a.b)++
而不是a.(b++)
。
C11 standard (ISO/IEC 9899:2011):
A.2.1 Expressions
C99 standard (ISO/IEC 9899:1999):
A.2.1 Expressions
C89/C90 standard (ISO/IEC 9899:1990):
A.1.2.1 Expressions