I know that cout have buffer several days ago, and when I google it, it is said that the buffer is some like a stack and get the output of cout and printf from right to left, then put them out(to the console or file)from top to bottem. Like this,
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)
Then I write a code below,
#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; }
Under VS2005, the output is
i=0 i++=-1 i--=0 i=0 i++=-1 i--=0 9 8 7 9 8 7
It seems that the stack way is right~ However, I read C++ Primer Plus yesterday, and it is said that the cout work from left to right, every time return an object(cout), so ‘That’s the feature that lets you concatenate output by using insertion’. But the from left to right way can not explain cout<
Then Alnitak tell me that, ‘The << operator is really ostream& operator<<(ostream& os, int), so another way of writing this is: operator<< ( operator<< ( operator<< ( cout, a ), b ), c )’,
If the rightest argument is first evaluated, it can be some explained.
Now I’m confused about how cout’s buffer work, can somebody help me?
You are mixing a lot of things. To date:
coutTry to read up on them separately. And don’t think about all of them in one go.
The above line invokes undefined behavior. Read the FAQ 3.2. Note, what you observe is a side-effect of the function’s calling convention and the way parameters are passed in the stack by a particular implementation (i.e. yours). This is not guaranteed to be the same if you were working on other machines.
I think you are confusing the order of function calls with buffering. When you have a
coutstatement followed by multiple insertions<<you are actually invoking multiple function calls, one after the other. So, if you were to write:It really means: You call,
and then use the return in another call to the same operator as:
What you have tested by the above will not tell you anything
cout‘s internal representation. I suggest you take a look at the header files to know more.