|
阅读:937回复:5
int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
我在VC 6.0中编程计算结果是13,我以为是12,要不然我怎么会上来请教各位啊,请问这是怎么回事???
下面是源程序: #include <iostream.h> void main() { int x=3; cout<<"(x--)+(x++)+(++x)+(--x)="<<(x--)+(x++)+(++x)+(--x);" } 下面是运行结果: (x--)+(x++)+(++x)+(--x)=13 |
|
|
|
1C#
发布于:2004-02-07 09:19
Re:int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
我记得有人曾经为类似的问题专门向BS提出过问题,他的回答是:
You are modifying a variable in an expression that uses it twice. That's 就是说这样的行为没有定义。 而且在C++ Primer中也明确指出,运算符左右的计算顺序在C/C++中都没有规定,所以运算必须是顺序无关的。当然逻辑运算除外! |
|
|
2C#
发布于:2004-02-07 09:56
Re:int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
6: int x = 3, y;
00401588 mov dword ptr [ebp-4],3 " x = 3; 7: y = (x--)+(x++)+(++x)+(--x); 0040158F mov eax,dword ptr [ebp-4] " eax = 3; x-- 00401592 add eax,dword ptr [ebp-4] " eax = 6; (x--)+(x++) 00401595 mov ecx,dword ptr [ebp-4] " ecx = 3; 00401598 add ecx,1 " ecx = 4; (++x) 0040159B mov dword ptr [ebp-4],ecx " x = 4; 0040159E add eax,dword ptr [ebp-4] " eax = 10; (x--)+(x++)+(++x) 004015A1 mov edx,dword ptr [ebp-4] " edx = 4; 004015A4 sub edx,1 " edx = 3; (--x) 004015A7 mov dword ptr [ebp-4],edx " x = 3; 004015AA add eax,dword ptr [ebp-4] " eax = 13; (x--)+(x++)+(++x)+(--x) 004015AD mov dword ptr [ebp-8],eax " y = 13; 004015B0 mov eax,dword ptr [ebp-4] " eax = 3; 004015B3 add eax,1 " eax = 4; x++ 004015B6 mov dword ptr [ebp-4],eax " x = 4; 004015B9 mov ecx,dword ptr [ebp-4] " ecx = 4; 004015BC sub ecx,1 " ecx = 3; x-- 004015BF mov dword ptr [ebp-4],ecx " x = 3; 这是在VC++中的汇编代码,非常清楚的说明了VC的运算顺序。 [ 2004-02-07 10:00:02 ApH 修改 ] |
|
|
3C#
发布于:2004-02-07 12:02
Re:int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
刚过完年就看到这么强的程序,真是牛啊! |
|
|
|
4C#
发布于:2004-02-07 13:39
Re:int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
牛人牛人,越来越佩服 ApH 大仙了。我要拜你为师 |
|
|
|
5C#
发布于:2004-02-11 16:54
Re:int x=3;那么(x--)+(x++)+(++x)+(--x)的值是什么?转帖]
口算就行了嘛 |
|
|