A brief analysis of the operation mechanism of cout in C++

  • 2020-04-02 01:41:19
  • OfStack


#include <iostream>
using namespace std;
int hello1();
int hello2();
int main() 
{
    int a, b;
    cout<<"a="<<hello1()<<" b="<<hello2()<<endl;
    return 0;}
int hello1()
{
    cout<<"hello1"<<endl;
    return 1;
}
int hello2() 
{
    cout<<"hello2"<<endl;
    return 2;
}

The final output is:
hello2
hello1
A = 1, b = 2

A bit of a puzzle for a moment, the web offers a reliable explanation: the sequence of operations for a cout stream is: read the buffer from right to left, then output from left to right. So when it reads from the right to the left, it hits the function and of course it executes the function first, then it reads the return value of the function into the buffer and then... That's output from the left.

According to this explanation, there are several experimental procedures that can deepen the understanding

Procedure 1:


#include <iostream>
using namespace std;
int main() 
{ 
    int b[2]={1,2};
    int *a=b;
    cout<<*a<<" "<<*(a++)<<endl;
    return 0; 
}

Output: 2, 1.
Explanation: read * (a++) first, for a++, is read into the buffer first, its self-increment, so, at this time in the buffer a is 1,. I'm going to read in *a, and now a has grown, so I'm going to read in 2.

Program 2:


#include <iostream>
using namespace std;
int main() 
{ 
    int i=5;
    cout<<i<<" "<<(i++)<<" "<<(++i)<<endl;
    return 0; 
}

The output is: 7, 6, 6
Explanation: from right to left, first (++ I), that is, the first increment, and then read into the buffer, is 6. And then (i++), which is read into the buffer, which is 6, and then self-increment. And then finally I, read buffer 7.


Related articles: