二話不說,先看一個例子
#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在執行的時候為從右向左先執行,然后在輸出的時候為按照原來的順序在從左像右的輸出。
