转自:http://blog.sina.com.cn/s/blog_46b7d6050100kxao.html
printf()输出表达式的运算顺序是由右向左的,不同的编译系统不一定相同,可以从左到右, 也可从右到左。Turbo C,VC++6.0都是按从右到左进行的。
写出程序的输出结果:
#include <stdio.h>
void main()
{
用VC++6.0环境运行,输出结果为:9,10,9,10,对于这个结果我很纳闷,为什么j=10?
原来问题出在n=j++,这个语句相当于:n=j,j=j+1;也就是说程序在本条输出语句结束以后,才计算j=j+1。于是在程序中增加了一行输出j的语句:printf("j=%d",j);果然,输出了j=11。
注意:
求值顺序是自右至左;
输出顺序还是从左至右.
Cout输出顺序:
转自:http://blog.csdn.net/wuxuzhao/article/details/7429733
<span style="font-size:14px;">#include <iostream>
using namespace std;
int a=0;
int fun1( )
{
cout << "f1"<<endl;;
a++;
return a;
}
int fun2( )
{
cout << "f2"<<endl;;
a++;
return a;
}
int main()
{
int i = 1;
cout << "m" <<endl<< fun1() <<endl<< fun2()<<endl;
return 1;
} </span>
cout << "m" <<endl<< fun1() <<endl<< fun2()<<endl;这句代码应该理解为:
operator<<(cout,"m",endl,fun1(),endl,fun2(),endl);
按C /C++调用约定,参数从右到左压入堆栈区:
1.fun2()入栈,输出"f2";
2.fun1()入栈,输出"f1";
3.cout对象入栈;
4.最后调用operator<<(cout,"m",endl,fun1()的返回值,endl,fun2()的返回值,endl);
输出结果为:
f2
f1
m
2
1
<pre name="code" class="cpp">int main()
{
int arr[]={6,7,8,9,10};
int *ptr=arr;
*(ptr++)+=123;
//printf("%d%d\n",*ptr,*(++ptr));
cout<<*ptr<<endl;
cout<<*(ptr++)<<endl;
cout<<*ptr<<endl;
return 0;
}
输出结果为:7 7 8
若输出为:
printf("%d%d\n",*ptr,*(++ptr));
输出结果:8 8
</pre><pre name="code" class="cpp">若输出为:
cout<<*ptr<<*(ptr++)<<endl;
输出结果:7 8