C++运算符优先级

 

 

C++运算符优先级理解记忆

C++运算符的优先级共分为16级,理解记忆如下:

四大层次

首先记忆四个大的层次:域天斗地单先赋值后

·域限定(::)优先级最高,逗号运算符优先级最低(两个特殊级别)

·单目运算符优先级第二高,赋值运算符第二低(理解:单目运算必须完成后才可能参与双目运算,所以优先级当然较高;赋值操作需要等表达式其他部分得到结果后再进行,优先级自然较低)

·(其余运算符优先级排中间)

层次细分

接下来把大的层次展开一下:

单目运算符

后缀运算符优先,前缀次之(两个层次)

后缀运算符中包括:成员括号后增减

    成员运算符:.及->。理解:看到myclass.abc、p->xxx.yyy可以理解为一个变量标识整体

    括号:包括()及[]。这里()是指函数调用的括号,[]是下标运算符。

    后增减:后缀形式的++、--。

 

前缀运算符中包括:正负非指先增减,创删大小与转换

其他运算符

C++运算符优先级全表

下表取自http://www.cplusplus.com/doc/tutorial/operators/

LevelPrecedence groupOperatorDescriptionGrouping
1Scope::scope qualifierLeft-to-right
2Postfix (unary)++ --postfix increment / decrementLeft-to-right
()functional forms
[]subscript
. ->member access
3Prefix (unary)++ --prefix increment / decrementRight-to-left
~ !bitwise NOT / logical NOT
+ -unary prefix
& *reference / dereference
new deleteallocation / deallocation
sizeofparameter pack
(type)C-style type-casting
4Pointer-to-member.* ->*access pointerLeft-to-right
5Arithmetic: scaling* / %multiply, divide, moduloLeft-to-right
6Arithmetic: addition+ -addition, subtractionLeft-to-right
7Bitwise shift<< >>shift left, shift rightLeft-to-right
8Relational< > <= >=comparison operatorsLeft-to-right
9Equality== !=equality / inequalityLeft-to-right
10And&bitwise ANDLeft-to-right
11Exclusive or^bitwise XORLeft-to-right
12Inclusive or|bitwise ORLeft-to-right
13Conjunction&&logical ANDLeft-to-right
14Disjunction||logical ORLeft-to-right
15Assignment-level expressions= *= /= %= += -=
>>= <<= &= ^= |=
assignment / compound assignmentRight-to-left
?:conditional operator
16Sequencing,comma separatorLeft-to-right

 

### C++ 运算符优先级C++运算符优先级定义了表达式中各运算符的计算顺序。当一个复杂表达式包含多个运算符时,优先级较高的运算符会先被执行[^1]。 以下是完整的 C++ 运算符优先级列表(从高到排列),涵盖了大部分常见的运算符: #### 单目运算符 | 优先级 | 类型 | 运算符 | |--------|--------------------|---------------------------------| | 1 | 后缀 | `()`, `[]`, `->`, `.`, `postfix ++`, `postfix --`[^5] | | 2 | 前缀 | `prefix ++`, `prefix --`, `+`, `-`, `!`, `~`, `(type)`, `*`, `&`, `sizeof`, `new`, `delete`[^3] | #### 多目运算符 | 优先级 | 类型 | 运算符 | |--------|------------------|------------------------------| | 3 | 成员访问 | `.*`, `->*` | | 4 | 求值 | `*`, `/`, `%` | | 5 | 加减法 | `+`, `-` | | 6 | 移位操作 | `<<`, `>>` | | 7 | 关系比较 | `<`, `>`, `<=`, `>=` | | 8 | 相等性判断 | `==`, `!=` | | 9 | 逻辑与 | `&` | | 10 | 逻辑异 | `^` | | 11 | 逻辑 | `\|` | | 12 | 条件测试 | `&&` | | 13 | 者条件测试 | `\|\|` | | 14 | 条件表达式 | `?:` | | 15 | 赋值 | `=`, `+=`, `-=` , `*=` , `/=`, etc.| 需要注意的是,在某些情况下,即使知道了运算符优先级,仍然可能需要通过显式的括号来改变默认的求值顺序[^4]。 对于 C++17 及之后的标准版本新增的一些特殊用途运算符未在此表格中列出,例如三向比较运算符 (`<=>`) 等[^2]。 ```cpp // 示例代码展示如何利用优先级解析表达式 int a = 5, b = 3; bool result = (a + b * 2 >= 10 && !(b < 2)); // 正确理解此语句需掌握优先级规则 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值