luc*_*cas 1 printf buffer cout
我知道cout和printf今天有缓冲区,据说缓冲区有点像堆栈,从右到左得到cout和printf的输出,然后从顶部到bottem将它们(到控制台或文件)放出.像这样,
a = 1; b = 2; c = 3;
cout<<a<<b<<c<<endl;
buffer?|3|2|1|<- (take “<-” as a poniter)
output?|3|2|<- (output 1)
|3|<- (output 2)
|<- (output 3)
Run Code Online (Sandbox Code Playgroud)
然后我写下面的代码,
#include <iostream>
using namespace std;
int c = 6;
int f()
{
c+=1;
return c;
}
int main()
{
int i = 0;
cout <<"i="<<i<<" i++="<<i++<<" i--="<<i--<<endl;
i = 0;
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
cout<<f()<<" "<<f()<<" "<<f()<<endl;
c = 6;
printf("%d %d %d\n" , f() , f() ,f() );
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在VS2005下,输出为
i=0 i++=-1 i--=0
i=0 i++=-1 i--=0
9 8 7
9 8 7
Run Code Online (Sandbox Code Playgroud)
在g ++((GCC)3.4.2(mingw-special))下,输出是,
i=0 i++=0 i--=1
i=0 i++=-1 i--=0
9 8 7
9 8 7
Run Code Online (Sandbox Code Playgroud)
似乎缓冲区就像一个堆栈.但是,我今天读了C++ Primer Plus,据说cout从左到右工作,每次都返回一个对象(cout),所以"这就是让你通过插入连接输出的功能".但是从左到右的方式无法解释cout <输出9 8 7现在我对cout缓冲区如何工作感到困惑,有人可以帮助我吗?
小智 6
输出:
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
Run Code Online (Sandbox Code Playgroud)
没有具体说明.这是C++的常见缺陷:参数评估顺序未指定.
cout案例不是这样:它使用链式调用(序列点),而不是单个函数的参数,因此评估顺序从左到右很好地定义.
编辑: David Thornley指出上述代码的行为实际上是未定义的.