读书人

运算符优先级解决方法

发布时间: 2013-11-15 22:28:15 作者: rapoo

运算符优先级
int a = 8;
int b = 4;
c = a++%++b*2;
按照优先级,++和*同级(从右到左),最后算%
所以不应该是 c = 8%(++8), c = 8%9,结果为什么不是8而是6?运算符优先级解决方法


这个是VC下生成的汇编代码:
可以结合看一下就明白了:运算符优先级解决方法
int a = 8;
0041180E mov dword ptr [a],8
int b = 4;
00411815 mov dword ptr [b],4
int c = a++%++b*2;
0041181C mov eax,dword ptr [b]
0041181F add eax,1
00411822 mov dword ptr [b],eax
00411825 mov eax,dword ptr [a]
00411828 cdq
00411829 idiv eax,dword ptr [b]
0041182C shl edx,1
0041182E mov dword ptr [c],edx
00411831 mov ecx,dword ptr [a]
00411834 add ecx,1
00411837 mov dword ptr [a],ecx
return 0;
0041183A xor eax,eax

先算++b,于是b的值为5,再算a%b,得到余值为3,再算3*2,得到6赋值给c。
[解决办法]
JScript

Unsigned Right Shift Operator (>>>)See Also
>>>= Operator
[解决办法]
<< Operator
[解决办法]
>> Operator
[解决办法]
Operator Precedence
[解决办法]
Operator Summary
Requirements
Version 1
Right shifts the bits of an expression, without maintaining sign.

result = expression1 >>> expression2
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroes are filled in from the left. Digits shifted off the right are discarded. For example:

var temp
temp = -14 >>> 2
The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary) shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary).

Requirements
Version 1

See Also
>>>= Operator
[解决办法]
<< Operator
[解决办法]
>> Operator
[解决办法]
Operator Precedence
[解决办法]
Operator Summary



--------------------------------------------------------------------------------

读书人网 >C++

热点推荐