12、C++操作符优先级:
记忆方法:
去掉一个最高的,去掉一个最低的,剩下的是一、二、三、赋值;双目运算符中,顺序为算术、关系和逻辑,移位和逻辑位插入其中。
--摘自《C语言程序设计实用问答》
问题:如何记住运算符的15种优先级和结合性?
解答:C语言中运算符种类比较繁多,优先级有15种,结合性有两种。
如何记忆两种结合性和15种优先级?下面讲述一种记忆方法。
结合性有两种,一种是自左至右,另一种是自右至左,大部分运算符的结合性是自左至右,只有单目运算符、三目运算符的赋值运算符的结合性自右至左。
优先级有15种,记忆方法如下:
记住一个最高的:构造类型的元素或成员以及小括号。
记住一个最低的:逗号运算符。
剩余的是一、二、三、赋值--意思是单目、双目、三目和赋值运算符。
在诸多运算符中,又分为:算术、关系、逻辑。
两种位操作运算符中,移位运算符在算术运算符后边,逻辑位运算符在逻辑运算符的前面。
再细分如下:
算术运算符*,/,%高于+,-。
关系运算符中:>,>=,age = 34;
yes |
. |
Member access from an object |
obj.age = 34; |
no |
++ |
Post-increment |
for (int i = 0; i < 10; i++) cout 0; i--) cout *var = 24; |
yes |
left to right |
.* |
Member object selector |
obj.*var = 24; |
no |
5 |
* |
Multiplication |
int i = 2 * 4; |
yes |
left to right |
/ |
Division |
float f = 10.0 / 3.0; |
yes |
% |
Modulus |
int rem = 4 % 3; |
yes |
6 |
+ |
Addition |
int i = 2 + 3; |
yes |
left to right |
- |
Subtraction |
int i = 5 - 1; |
yes |
7 |
| > 1;
yes |
8 |
| =
Comparison greater-than-or-equal-to |
if (i >= 42) ... |
yes |
9 |
== |
Comparison equal-to |
if (i == 42) ... |
yes |
left to right |
eq |
Alternate spelling for == |
!= |
Comparison not-equal-to |
if (i != 42) ... |
yes |
not_eq |
Alternate spelling for != |
10 |
& |
Bitwise AND |
flags = flags & 42; |
yes |
left to right |
bitand |
Alternate spelling for & |
11 |
^ |
Bitwise exclusive OR (XOR) |
flags = flags ^ 42; |
yes |
left to right |
xor |
Alternate spelling for ^ |
12 |
| |
Bitwise inclusive (normal) OR |
flags = flags | 42; |
yes |
left to right |
bitor |
Alternate spelling for | |
13 |
&& |
Logical AND |
if (conditionA && conditionB) ... |
yes |
left to right |
and |
Alternate spelling for && |
14 |
|| |
Logical OR |
if (conditionA || conditionB) ... |
yes |
left to right |
or |
Alternate spelling for || |
15 |
? : |
Ternary conditional (if-then-else) |
int i = a > b ? a : b; |
no |
right to left |
16 |
= |
Assignment operator |
int a = b; |
yes |
right to left |
+= |
Increment and assign |
a += 3; |
yes |
-= |
Decrement and assign |
b -= 4; |
yes |
*= |
Multiply and assign |
a *= 5; |
yes |
/= |
Divide and assign |
a /= 2; |
yes |
%= |
Modulo and assign |
a %= 3; |
yes |
&= |
Bitwise AND and assign |
flags &= new_flags; |
yes |
and_eq |
Alternate spelling for &= |
^= |
Bitwise exclusive or (XOR) and assign |
flags ^= new_flags; |
yes |
xor_eq |
Alternate spelling for ^= |
|= |
Bitwise normal OR and assign |
flags |= new_flags; |
yes |
or_eq |
Alternate spelling for |= |
= 2; |
yes |
17 |
throw |
throw exception |
throw EClass("Message"); |
no |
|
18 |
, |
Sequential evaluation operator |
for (i = 0, j = 0; i < 10; i++, j++) ... |
yes |
left to right |
点击加载更多评论>>