函数式编程 - 按值传递



在定义函数后,我们需要将参数传入其中以获取所需的结果。大多数编程语言都支持将参数传递给函数的按值传递按引用传递方法。

在本章中,我们将学习“按值传递”是如何在面向对象编程语言(如 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 
广告