[转]C++中运算符优先级表

来源:互联网 发布:mac 获取当前用户名 编辑:程序博客网 时间:2024/06/05 11:52

小记

      虽然自己不会写那些优雅紧凑的C代码,但是偶尔看一些代码(比如GNU项目的源代码和Linux内核源代码)时,还是需要仔细查阅和分析运算符优先级的。

Precedence

Operator

Description

Example

Associativity

1

()
[]
->
.
::
++
--

Groupingoperator
Array access
Member access from a pointer
Memberaccess from an object
Scopingoperator
Post-increment
Post-decrement

(a + b) /4;
array[4] = 2;
ptr->age = 34;
obj.age =34;
Class::age = 2;
for( i = 0; i < 10; i++ ) ...
for(i = 10; i > 0; i-- ) ...

left toright

2

!
~
++
--
-
+
*
&
(type)
sizeof

Logicalnegation
Bitwise complement
Pre-increment
Pre-decrement
Unaryminus
Unary plus
Dereference
Address of
Cast to agiven type
Return size in bytes

if( !done )...
flags = ~flags;
for( i = 0; i < 10; ++i ) ...
for(i = 10; i > 0; --i ) ...
int i = -1;
int i = +1;
data= *ptr;
address = &obj;
int i = (int) floatNum;
intsize = sizeof(floatNum);

right toleft

3

->*
.*

Memberpointer selector
Member pointer selector

ptr->*var= 24;
obj.*var = 24;

left toright

4

*
/
%

Multiplication
Division
Modulus

int i = 2 *4;
float f = 10 / 3;
int rem = 4 % 3;

left toright

5

+
-

Addition
Subtraction

int i = 2 +3;
int i = 5 - 1;

left toright

6

<<
>>

Bitwiseshift left
Bitwise shift right

int flags =33 << 1;
int flags = 33 >> 1;

left toright

7

<
<=
>
>=

Comparisonless-than
Comparison less-than-or-equal-to
Comparisongreater-than
Comparison geater-than-or-equal-to

if( i <42 ) ...
if( i <= 42 ) ...
if( i > 42 ) ...
if( i>= 42 ) ...

left toright

8

==
!=

Comparisonequal-to
Comparison not-equal-to

if( i == 42) ...
if( i != 42 ) ...

left toright

9

&

Bitwise AND

flags =flags & 42;

left toright

10

^

Bitwiseexclusive OR

flags =flags ^ 42;

left toright

11

|

Bitwiseinclusive (normal) OR

flags =flags | 42;

left toright

12

&&

Logical AND

if(conditionA && conditionB ) ...

left toright

13

||

Logical OR

if(conditionA || conditionB ) ...

left toright

14

? :

Ternaryconditional (if-then-else)

int i = (a> b) ? a : b;

right toleft

15

=
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=

Assignmentoperator
Increment and assign
Decrement and assign
Multiplyand assign
Divide and assign
Modulo and assign
BitwiseAND and assign
Bitwise exclusive OR and assign
Bitwiseinclusive (normal) OR and assign
Bitwise shift left andassign
Bitwise shift right and assign

int a =b;
a += 3;
b -= 4;
a *= 5;
a /= 2;
a %= 3;
flags&= new_flags;
flags ^= new_flags;
flags |=new_flags;
flags <<= 2;
flags >>= 2;

right toleft

16

,

Sequentialevaluation operator

for( i = 0,j = 0; i < 10; i++, j++ ) ...

left toright

某个口诀,帮忙记忆 

阔框点箭域先锋 ① () [] . -> :: 
塞外干旱烦政府 ②sizeof ! ~ + - 
家家户户限制米 ++ -- (type型) &(取址) * 
救灾捐米一点米 ③->* .* 
时余曾促物价减 ④% * / ⑤+ - 
左邻右舍来相告 ⑥<< >> 
老大小凳换大凳 ⑦> < <= >= 
把事说明等不等 ⑧== != 
久雨适宜事宜否 ⑨&⑩^⑾| 
十二雨下十三过 ⑿&&⒀|| 
三梦睡醒灯都灭 ⒁:?(三目运算) ⒂= +=...⒃,(逗号) 

老实说,我觉的将运算符优先级背下来实在是太坑爹了,想用的时候多用用括号就行了,在此挖苦一下中国式的程序语言教学,把时间浪费在研究诸如 *--p++-- - --q++之类的东西上。
转自:http://www.cppblog.com/aqazero/archive/2006/06/08/8284.html