函數語言程式設計 - 按值傳遞



在定義函式後,我們需要將引數傳入其中以獲取所需的結果。大多數程式語言都支援將引數傳遞給函式的按值傳遞按引用傳遞方法。

在本章中,我們將學習“按值傳遞”是如何在面向物件程式語言(如 C++)和函數語言程式設計語言(如 Python)中工作的。

在按值傳遞方法中,原始值不可更改。當我們向函式傳遞引數時,它會由函式引數儲存在堆疊記憶體中。因此,該值的更改只在函式內部發生,在函式外部不會有影響。

在 C++ 中按值傳遞

以下程式展示了按值傳遞如何在 C++ 中工作 -

#include <iostream> 
using namespace std; 

void swap(int a, int b) {    
   int temp; 
   temp = a; 
   a = b; 
   b = temp; 
   cout<<"\n"<<"value of a inside the function: "<<a; 
   cout<<"\n"<<"value of b inside the function: "<<b; 
}  
int main() {     
   int a = 50, b = 70;   
   cout<<"value of a before sending to function: "<<a; 
   cout<<"\n"<<"value of b before sending to function: "<<b; 
   swap(a, b);  // passing value to function 
   cout<<"\n"<<"value of a after sending to function: "<<a; 
   cout<<"\n"<<"value of b after sending to function: "<<b; 
   return 0;   
}  

將產生以下輸出 -

value of a before sending to function:  50 
value of b before sending to function:  70 
value of a inside the function:  70 
value of b inside the function:  50 
value of a after sending to function:  50 
value of b after sending to function:  70 

在 Python 中按值傳遞

以下程式顯示了按值傳遞如何在 Python 中工作 -

def swap(a,b): 
   t = a; 
   a = b; 
   b = t; 
   print "value of a inside the function: :",a 
   print "value of b inside the function: ",b 

# Now we can call the swap function 
a = 50 
b = 75 
print "value of a before sending to function: ",a 
print "value of b before sending to function: ",b 
swap(a,b) 
print "value of a after sending to function: ", a 
print "value of b after sending to function: ",b 

將產生以下輸出 -

value of a before sending to function:  50 
value of b before sending to function:  75 
value of a inside the function: : 75 
value of b inside the function:  50 
value of a after sending to function:  50 
value of b after sending to function:  75 
廣告