C++运算符优先级理解记忆
C++运算符的优先级共分为16级,理解记忆如下:
四大层次
首先记忆四个大的层次:域天斗地单先赋值后
·域限定(::)优先级最高,逗号运算符优先级最低(两个特殊级别)
·单目运算符优先级第二高,赋值运算符第二低(理解:单目运算必须完成后才可能参与双目运算,所以优先级当然较高;赋值操作需要等表达式其他部分得到结果后再进行,优先级自然较低)
·(其余运算符优先级排中间)
层次细分
接下来把大的层次展开一下:
单目运算符
后缀运算符优先,前缀次之(两个层次)
后缀运算符中包括:成员括号后增减
成员运算符:.及->。理解:看到myclass.abc、p->xxx.yyy可以理解为一个变量标识整体
括号:包括()及[]。这里()是指函数调用的括号,[]是下标运算符。
后增减:后缀形式的++、--。
前缀运算符中包括:正负非指先增减,创删大小与转换
其他运算符
C++运算符优先级全表
下表取自http://www.cplusplus.com/doc/tutorial/operators/
Level | Precedence group | Operator | Description | Grouping |
---|---|---|---|---|
1 | Scope | :: | scope qualifier | Left-to-right |
2 | Postfix (unary) | ++ -- | postfix increment / decrement | Left-to-right |
() | functional forms | |||
[] | subscript | |||
. -> | member access | |||
3 | Prefix (unary) | ++ -- | prefix increment / decrement | Right-to-left |
~ ! | bitwise NOT / logical NOT | |||
+ - | unary prefix | |||
& * | reference / dereference | |||
new delete | allocation / deallocation | |||
sizeof | parameter pack | |||
(type) | C-style type-casting | |||
4 | Pointer-to-member | .* ->* | access pointer | Left-to-right |
5 | Arithmetic: scaling | * / % | multiply, divide, modulo | Left-to-right |
6 | Arithmetic: addition | + - | addition, subtraction | Left-to-right |
7 | Bitwise shift | << >> | shift left, shift right | Left-to-right |
8 | Relational | < > <= >= | comparison operators | Left-to-right |
9 | Equality | == != | equality / inequality | Left-to-right |
10 | And | & | bitwise AND | Left-to-right |
11 | Exclusive or | ^ | bitwise XOR | Left-to-right |
12 | Inclusive or | | | bitwise OR | Left-to-right |
13 | Conjunction | && | logical AND | Left-to-right |
14 | Disjunction | || | logical OR | Left-to-right |
15 | Assignment-level expressions | = *= /= %= += -= | assignment / compound assignment | Right-to-left |
?: | conditional operator | |||
16 | Sequencing | , | comma separator | Left-to-right |