c++cout执行顺序之一个不容易注意到的一点

二话不说,先看一个例子

#include <iostream>

using namespace std;

int main()
{
    int a[10]={1,12,34,56,78,89,90,8,9,0};
    int *p=a;
    int *p2=a;
    cout<<++*p<<endl;
    cout<<*++p<<endl;//谁靠的近先执行谁
    cout<<endl;
    cout<<++*p2<<"    "<<*p2<<"    "<<*++p2<<endl;
    char *st[]={"asd","qwe","zxc"};
    char**q=st;
    cout<<*++q<<endl;
    cout<<*q<<endl;
    return 0;
}

运行结果

2
12

13    12    12
qwe
qwe

是不是很interesting,本来是探究++与解指针运算符*的优先级的问题,引发了一个有关cout执行顺序的问题。
其实这两的优先级一样都为2

为什么p2的输出就成了这个样子,而并不是我们所认为的2    2    12.

种种事实表明,cout的运行时候执行顺序是从右往左,是符合栈的执行模型的。再来个例子

#include <iostream>

using namespace std;

int  f1()
{
    cout<<"f1"<<endl;
    return 1;
}
int  f2()
{
    cout<<"f2"<<endl;
    return 2;
}
int  f3()
{
    cout<<"f3"<<endl;
    return 3;
}

int main()
{
    cout <<"first--"<<f1()<<"   second--"<<f2()<<"   third--"<<f3()<< endl;
    return 0;
}

 可以看到运行结果为

f3
f2
f1
first--1   second--2   third--3

Process returned 0 (0x0)   execution time : -0.000 s
Press any key to continue.

这明显证明cout在执行的时候为从右向左先执行,然后在输出的时候为按照原来的顺序在从左像右的输出

原文地址:https://www.cnblogs.com/freedom314/p/5864365.html