C++ 值傳遞函式呼叫



將引數傳遞給函式的值傳遞方法將引數的實際值複製到函式的形式引數中。在這種情況下,在函式內部對引數所做的更改不會影響引數。

預設情況下,C++ 使用值傳遞來傳遞引數。通常,這意味著函式內的程式碼無法更改用於呼叫函式的引數。考慮以下函式swap()定義。

// function definition to swap the values.
void swap(int x, int y) {
   int temp;

   temp = x; /* save the value of x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}

現在,讓我們透過傳遞實際值來呼叫函式swap(),如下例所示:

#include <iostream>
using namespace std;
 
// function declaration
void swap(int x, int y);
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;
 
   // calling a function to swap the values.
   swap(a, b);
 
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}

當以上程式碼放在一個檔案中,編譯並執行時,會產生以下結果:

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

這表明儘管在函式內部更改了值,但值沒有發生變化。

cpp_functions.htm
廣告