按价值传递

按价值传递 首页 / 函数式入门教程 / 按价值传递

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

在本章中,我们将学习"call by value"在面向对象的编程语言(如C++)和函数式编程语言(如Python)中的工作。

在"call by value "方法中,原始值无法更改,当我们将参数传递给函数时,它由函数参数本地存储在堆栈存储器中。因此仅在函数内部更改值,并且不会在函数外部产生影响。

在C ++中按值调用

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

无涯教程网

#include <iostream> 
using namespace std; 

void learnfk_swap(int a, int b) {    
   int temp; 
   temp = a; 
   a = b; 
   b = temp; 
   cout<<"\n"<<"函数内部 a 的值: "<<a; 
   cout<<"\n"<<"函数内部 b 的值: "<<b; 
}  
int main() {     
   int a = 50, b = 70;   
   cout<<"传递前 a 值: "<<a; 
   cout<<"\n"<<"传递前 b 的值: "<<b; 
learnfk_swap(a, b); //参数传递 cout<<"\n"<<"传递后 a 值: "<<a;
cout<<"\n"<<"传递后 b 值: "<<b;
return 0; }

它将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/functional-programming/functional-programming-call-by-value.html

来源:LearnFk无涯教程网

传递前 a 值:  50 
传递前 b 值:  70 
函数内部 a 的值:  70 
函数内部 b 的值:  50 
传递后 a 值: 50 传递后 b 值: 70

在Python中按值调用

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

def learnfk_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 
learnfk_swap(a,b) 
print "value of a after sending to function: ", a 
print "value of b after sending to function: ",b 

它将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/functional-programming/functional-programming-call-by-value.html

来源:LearnFk无涯教程网

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 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

邱岳的产品手记 -〔邱岳〕

邱岳的产品实战 -〔邱岳〕

互联网人的英语私教课 -〔陈亦峰〕

手把手带你搭建秒杀系统 -〔佘志东〕

PyTorch深度学习实战 -〔方远〕

郭东白的架构课 -〔郭东白〕

计算机基础实战课 -〔彭东〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

好记忆不如烂笔头。留下您的足迹吧 :)