返回信息流# 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的?
这是一条镜像帖。来源:北邮人论坛 / cpp / #43648同步于 2010/9/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
请教前增量与后增量
ztkldxfdhy
2010/9/9镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
g++输出结果
C:\WINDOWS\system32\cmd.exe /c test
3
3
b=4
a=4
Hit any key to close this window...
【 在 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的?
$ 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.
: ...................