C/C++中的按值調用與按引用調用

來源:互聯網
上載者:User

 許多程式設計語言中的調用函數的兩種方法是按值調用(call-by-value)和按引用調用(call-by-reference)。

參數按值調用傳遞時,產生參數值副本並且傳給被調用函數,副本的改變並不影響調用者的原始變數值,這樣就可以防止意外的副作用影響開發正確,可靠的系統。按值調用的一個缺點是,如果傳遞較大的資料項目,則複製這個資料可能要佔用相當長的執行時間。

 

而引用調用,調用者讓被調用者函數能夠直接存取調用者的資料,並且允許被調用函數能夠修改其中的資料。

引用調用對效能有利,消除了賦值大量資料的開銷。

 

下面為<<C++大學教程>>中介紹的例子:

 

#include<cstdlib>

#include<iostream>

 

using namespace std;

int squareByValue(int);
void squareByReference(int &);

int main(){
     int x = 2,z = 4;
     cout << "x = " << x << " before squareByValue/n"
             << "Value returned by squareByValue:"
             << squareByValue(x) << endl
             << "x= " << x << " after squareByValue/n" << endl;
     cout << "z= " << z << " before squareByReference" << endl;
     squareByReference(z);
     cout << "z= " << z << " after squareByReference" << endl;
     return 0;
}

int squareByValue(int a){
        return a *= a;
}

void squareByReference(int &cRef){
        cRef *= cRef;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.