On the operating mechanism of cout in C + + _c language

Source: Internet
Author: User

Copy Code code as follows:

#include <iostream>
using namespace Std;
int Hello1 ();
int Hello2 ();

int main ()
{
int A, B;
cout<< "A=" <return 1;
}
int Hello2 ()
{
cout<< "Hello2" <<endl;
return 2;
}


The final output is:
Hello2
Hello1
A=1 b=2

It's a bit hard to figure out, and it's a plausible explanation on the Web: the Order of operations for cout streams is to read the buffer from right to left and then output from left to right. So when it reads from the right to the left, it touches the function, of course, executes the function first, then reads the function return value into the buffer and then ... is the output from the left.

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

Program 1:

Copy Code code as follows:

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

The output is: 2 1.
Interpretation: first read into the * (a++), for a++, is read into the buffer, its own, so, at this time the buffer of a is 1,. Read the *a again, at this time a has been increased, so read into the buffer is 2.

Program 2:

Copy Code code as follows:

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

Output is: 7 6 6
Explanation: From right to left, first (++i), that is, the first increment, then read into the buffer, 6. Again (i++), that is, read into the buffer first, to 6, and then increase itself. The last is I, read into the buffer is 7.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.