C++运算符优先级与结合性
最近总是由于不清楚运算符优先级不小心写错代码,每次都去查cppreference。现在把cppreference内容拷贝至此,方便查询。
这里面最值得注意的是<<(移位)优先级低于+/-(加减),!(逻辑非)++/--(自增/自减)+/-(正负)优先级低于->运算符。
优先级与结合性
下表列出了C++运算符的优先级和结合性。从上到下,运算符的优先级逐渐减弱.
| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 1 | ::
|
作用域解析 | Left-to-right |
| 2 | ++ --
|
后缀 自增、自减 | |
()
|
函数调用 | ||
[] |
数组下标 | ||
. |
通过引用选择成员 | ||
−> |
通过指针选择成员 | ||
| 3 | ++ --
|
前缀 自增、自减 | Right-to-left |
+ −
|
正、负 | ||
! ~
|
逻辑非、按位非 | ||
(type)
|
显式类型转换 | ||
*
|
解引用 | ||
&
|
取地址 | ||
sizeof
|
取对象大小 | ||
new, new[]
|
动态内存分配 | ||
delete, delete[]
|
动态内存去分配 | ||
| 4 | .* ->*
|
成员指针运算符 | Left-to-right |
| 5 | * / %
|
乘、除、求余 | |
| 6 | + −
|
加、减 | |
| 7 | << >>
|
按位左移、按位右移 | |
| 8 | < <=
|
小于、小于或等于 | |
> >=
|
大于、大于或等于 | ||
| 9 | == !=
|
等于、不等于 | |
| 10 | &
|
按位与 | |
| 11 | ^
|
按位异或 | |
| 12 | |
|
按位或 | |
| 13 | &&
|
逻辑与 | |
| 14 | ||
|
逻辑或 | |
| 15 | ?:
|
三目运算符 | Right-to-left |
=
|
赋值 | ||
+= −=
|
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 | ||
throw
|
Throw operator (for exceptions) | ||
| 17 | ,
|
Comma | Left-to-right |
运算符列表
| Common operators | ||||||
|---|---|---|---|---|---|---|
| assignment | increment decrement |
arithmetic | logical | comparison | member access |
other |
|
a = b |
++a |
+a |
!a |
a == b |
a[b] |
a(...) |
| Special operators | ||||||
|
static_cast converts one type to another compatible type | ||||||
本文采用 知识共享署名 4.0 国际许可协议(CC-BY 4.0)进行许可,转载注明来源即可: https://harttle.land/2015/10/04/cpp-operator-precedence.html。如有疏漏、谬误、侵权请通过评论或 邮件 指出。