按引用、值和名称调用 [英] Call by reference, value, and name

查看:48
本文介绍了按引用、值和名称调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解按引用调用、值调用和名称调用之间的概念差异.

I'm trying to understand the conceptual difference between call by reference, value, and name.

所以我有以下伪代码:

foo(a, b, c)
{
   b =b++;
   a = a++;
   c = a + b*10
}

X=1;
Y=2;
Z=3;
foo(X, Y+2, Z);

如果 a、b 和 c 都是按引用调用,则 foo 调用后的 X、Y 和 Z 是什么?如果 a、b 和 c 是按值/结果调用?如果 a、b 和 c 是按名称调用?

What's X, Y, and Z after the foo call if a, b, and c are all call by reference? if a, b, and c are call-by-value/result? if a, b, and c are call-by-name?

另一种情况:

X=1;
Y=2;
Z=3;
foo(X, Y+2, X);

我正在努力为即将到来的期末考试抢占先机,这似乎是一个很好的复习题.Pass-by-name 对我来说绝对是最陌生的.

I'm trying to get a head start on studying for an upcoming final and this seemed like a good review problem to go over. Pass-by-name is definitely the most foreign to me.

推荐答案

当您按值传递参数时,它只是复制函数参数中的值,并且在函数中对该变量所做的任何操作都不会反映原始值变量例如

When you pass a parameter by value, it just copies the value within the function parameter and whatever is done with that variable within the function doesn't reflect the original variable e.g.

foo(a, b, c)
{
   b =b++;
   a = a++;
   c = a + b*10
}

X=1;
Y=2;
Z=3;
foo(X, Y+2, Z);
//printing will print the unchanged values because variables were sent by value so any //changes made to the variables in foo doesn't affect the original.
print X; //prints 1
print Y; //prints 2
print Z; //prints 3

但是当我们通过引用发送参数时,它会复制变量的地址,这意味着无论我们在函数内对变量做什么,实际上都是在原始内存位置完成的,例如

but when we send the parameters by reference, it copies the address of the variable which means whatever we do with the variables within the function, is actually done at the original memory location e.g.

foo(a, b, c)
{
   b =b++;
   a = a++;
   c = a + b*10
}

X=1;
Y=2;
Z=3;
foo(X, Y+2, Z);

print X; //prints 2
print Y; //prints 5
print Z; //prints 52

用于按名称传递;按名称传递

这篇关于按引用、值和名称调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆