C++中cout的運行機制

來源:互聯網
上載者:User

  關於C++中cout的使用,相信大家再熟悉不過了,然而對於cout是如何輸出的?輸出的機制是啥,需要進一步的瞭解。本章娓娓道來。前幾天在網上看到這麼一個題目:

View Code

#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;
}

最終輸出是:
hello2
hello1
a=1 b=2

一時讓人有點難以琢磨,網上給出了其靠譜的解釋:cout流的操作順序是:先從右往左讀入緩衝區,然後再從左往右輸出。所以它從右邊往左讀的時候,碰到了函數當然去執行函數先了,然後把函數傳回值讀入緩衝區再然後。。。就是從左輸出了。

  根據這個解釋,有實驗的幾個程式,能加深點理解

程式1:

View Code

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

輸為出:2 1。
解釋:先讀入*(a++),對於a++,是先讀入緩衝區,其自增,所以,此時緩衝區中的a是1,。再讀入*a,此時a已自增,所以讀入緩衝區的是2.

程式2:

View Code

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

輸出為:7 6 6
解釋:從右往左,先是(++i),即先自增,再讀入緩衝區,為6。再是(i++),即先讀入緩衝區,為6,再自增。最後是i,讀入緩衝區為7. 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.