BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #43648同步于 2010/9/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

请教前增量与后增量

ztkldxfdhy
2010/9/9镜像同步8 回复
# include<iostream.h> void main() { int a=2; cout<<(++a)<<endl; cout<<a<<endl; int b; cout<<"b="<<(b=++a)<<endl <<"a="<<a<<endl; } 运行结果是: 3 3 b=4 a=3 为什么第二行输出的值是有加1的 而第四行输出的值是没加1的?
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
zwp机器人#1 · 2010/9/9
LZ确定没写错?
nevermadao机器人#2 · 2010/9/9
我调试了一下,发现执行完之后b根本没有被赋值。 我想可能和引用有关,是不是<<(b=++a)<<,a,b都只是传了值。哪位大牛解释一下
y0192837465机器人#3 · 2010/9/9
用VS2010试了了一下,输出的结果是 3 3 b=4 a=4
zwp机器人#4 · 2010/9/9
g++输出结果 C:\WINDOWS\system32\cmd.exe /c test 3 3 b=4 a=4 Hit any key to close this window...
nevermadao机器人#5 · 2010/9/9
我用的是vc6.0,结果和楼主一样
wildpointer机器人#6 · 2010/9/9
【 在 ztkldxfdhy (Freshman) 的大作中提到: 】 : # include<iostream.h> : void main() : { : int a=2; : cout<<(++a)<<endl; : cout<<a<<endl; : int b; : cout<<"b="<<(b=++a)<<endl : <<"a="<<a<<endl; cout<<x; 相当于operator<<(cout,x); operator<<有两个参数,一个是cout, 一个是x cout<<x<<y;相当于 (cout<<x)<<y; 相当于 operator<<((cout<<x),y);operator<<有两个参数,一个是cout<<x, 一个是y. 函数的参数的求值顺序是不确定的。先对cout<<x求值,还是先对y求值,不确定。 cout<<(b=++a)<<a;相当于operator<<((cout<<(b=++a)), a);先对cout<<(b=++a)求值,还是先对第二个参数a求值是不确定的。 : } : 运行结果是: : 3 : 3 : b=4 : a=3 : 为什么第二行输出的值是有加1的 : 而第四行输出的值是没加1的?
wildpointer机器人#7 · 2010/9/9
$ nl -ba test.cpp 1 # include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a=2; 6 cout<<(++a)<<endl; 7 cout<<a<<endl; 8 int b; 9 cout<<"b="<<(b=++a)<<endl<<"a="<<a<<endl; 10 return 0; 11 } $ g++ test.cpp -Wall test.cpp: In function ‘int main()’: test.cpp:9: warning: operation on ‘a’ may be undefined $ ======================================================================= 1 # include<iostream> 2 #include <cstdio> 3 using namespace std; 4 int main() 5 { 6 int a=2; 7 cout<<(++a)<<endl; 8 cout<<a<<endl; 9 int b; 10 printf("%d %d", a, ++a); 11 cout<<"b="<<(b=++a)<<endl<<"a="<<a<<endl; 12 return 0; 13 } 知道第10行有什么问题,再知道<<是个重载的运算符,operator<<是个函数。也就知道第11行有什么问题。 【 在 wildpointer (NULL^2) 的大作中提到: 】 : cout<<x; 相当于operator<<(cout,x); operator<<有两个参数,一个是cout, 一个是x : cout<<x<<y;相当于 (cout<<x)<<y; : 相当于 operator<<((cout<<x),y);operator<<有两个参数,一个是cout<<x, 一个是y. : ...................
nuanyangyang机器人#8 · 2010/9/9
c语言为什么要这样呢,好奇怪。我觉得ruby的a+=1都很奇怪。为什么不是a=a+1呢。