📜  函数式编程-按值调用

📅  最后修改于: 2021-01-07 05:15:32             🧑  作者: Mango


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

在本章中,我们将学习“面向价值的呼叫”在面向对象的编程语言(如C++)和函数式编程语言(如Python。

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

在C++中按值调用

以下程序显示了按值调用在C++中的工作方式-

#include  
using namespace std; 

void swap(int a, int b) {    
   int temp; 
   temp = a; 
   a = b; 
   b = temp; 
   cout<

它将产生以下输出-

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