函数式编程 - 按值调用

定义函数后,我们需要将参数传递给它以获得所需的输出。 大多数编程语言都支持将参数传递给函数的按值调用按引用调用方法。

在本章中,我们将学习"按值调用"在面向对象编程语言(如 C++)和函数式编程语言(如 Python)中的工作原理。

在按值调用方法中,原始值无法更改。 当我们将参数传递给函数时,它由函数参数本地存储在堆栈内存中。 因此,这些值仅在函数内部更改,不会对函数外部产生影响。

C++ 中按值调用

以下程序显示了 C++ 中按值调用的工作原理 −

#include <iostream> 
using namespace std; 

void swap(int a, int b) {    
   int temp; 
   temp = a; 
   a = b; 
   b = temp; 
   cout<<"
"<<"value of a inside the function: "<<a; 
   cout<<"
"<<"value of b inside the function: "<<b; 
}  
int main() {     
   int a = 50, b = 70;   
   cout<<"value of a before sending to function: "<<a; 
   cout<<"
"<<"value of b before sending to function: "<<b; 
   swap(a, b);  // passing value to function 
   cout<<"
"<<"value of a after sending to function: "<<a; 
   cout<<"
"<<"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