3. 语法"陷阱"

1. C运算符优先级

运算符(优先级从高到低) 结合律
++(后置)、--(后置)、()(函数调用)、[]、{}、(复合字面量)、. 、-> 从左往右
++(前置)、--(前置)、-、+、~、!、*(解引用)、&(取址)、sizeof、_Alignof(类型名)(本栏都是一元运算符) 从右往左
(类型名) 从右往左
*、/、% 从左往右
+、-(都是二元运算符) 从左往右
<<、>> 从左往右
<、>、<=、>= 从左往右
==、!= 从左往右
& 从左往右
^ 从左往右
| 从左往右
&& 从左往右
|| 从左往右
?:(条件表达式) 从右往左
=、*=、/=、+=、-=、<<=、>>=、&=、|=、^= 从右往左
,(逗号运算符) 从左往右

注:以上优先级来自C Primer Plus第六版中文版

采用C缺陷与陷阱总结为:

  1. 非运算符和一元运算符
  2. 算数运算符
  3. 移位运算符
  4. 关系运算符
  5. 逻辑运算符
  6. 条件表达式
  7. 赋值运算符
  8. 逗号运算符

2. C++运算符优先级

 等级 结合律 运算符 功能 用法
1 :: 全局作用域 ::name
:: 类作用域 class::name
:: 命名空间作用域 namespace::name
2 . 成员选择 object.member
-> 成员选择 ptr->member
[] 下标 expr[expr]
() 函数调用 name(expr_list)
() 类型构造 type(expr_list)
3 ++ 后置递增运算  lvalue++
右  -- 后置递减运算 lvalue-- 
 typeid 类型ID typeid(type) 
 typeid 运行时类型ID typeid(expr) 
explicit_cast  类型转换 cast_name<type>(expr) 
4 ++   前值递增运算 ++lvalue
右  --  前置递减运算  --lvalue 
右  位求反  ~expr 
右  逻辑非  !expr
右  一元负号  -expr 
右  一元正号  +expr 
右  解引用  *expr 
右  取地址  &lvalue 
右  ()  类型转换  (type)expr 
右  sizeof  对象的大小  sizeof expr 
右  sizeof  类型的大小  sizeof(type) 
右  sizeof...  参数包的大小  sizeof...(name) 
右  new  创建对象  new type 
右  new[]  创建数组  new type[size] 
右  delete  释放对象  delete expr 
右  delete[]  释放数组  delete[] expr 
右  noexcept  能否抛出异常  noexpect(expr) 
5 ->* 指向成员选择的指针  ptr->*ptr_to_member
.* 指向成员选择的指针 obj.*ptr_to_member
6 乘法  expr * expr
除法 expr / expr 
左  取模(取余)  expr % expr 
7 + 加法 expr + expr
左  减法  expr - expr 
8 << 向左移位 expr << expr
>>  向右移位  expr >> expr 
9
   
< 小于 expr < expr
左  <=  小于等于  expr <= expr 
左  大于  expr > expr 
左  >=  大于等于  expr >= expr 
10 == 等于 expr == expr
左  !=  不等于  expr != expr 
11 & 位与 expr & expr
12 左  位异或  expr ^ expr 
13 左  位或  expr | expr 
14 左  &&  逻辑与  expr && expr 
15 左  ||  逻辑或  expr || expr 
16 ?: 条件 expr ? epxr : expr
17 赋值  lvaue = epxr
18 右  *=、/=、%= 复合赋值    lvalue += expr 等    
右   +=、-=
右  <<=、>>= 
右  &=、|=、^= 
19 throw  抛出异常 throw expr
20 左  逗号  expr, expr 

注:以上优先级来自C++ Primer 第五版中文版

大致运算符优先级同上

猜你喜欢

转载自www.cnblogs.com/hebust-fengyu/p/12031497.html
3.