返回值是多少?
在通过引用传递参数的语言中,给定以下函数:
int function g(x, y) {
x = x + 1;
y = y + 2;
return x + y;
}
如果调用i = 3
,并且调用g(i,i)
,则返回值是多少?我以为是9
,这是正确的吗?
In a language that passes parameters by reference, given the following function:
int function g(x, y) {
x = x + 1;
y = y + 2;
return x + y;
}
If i = 3
, and g(i,i)
is called, what is value returned? I thought it is 9
, is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果它是按引用传递(你原来的问题是 C,但 C 没有按引用传递,而且问题从那时起就发生了变化,所以我会笼统地回答),情况可能是
x
和y
将简单地修改为它们传入的变量。毕竟,这就是参考。在这种情况下,它们都是对相同变量
i
的引用,所以你的序列可能是:你可以在使用以下 C 进行操作(使用指针模拟传递引用):
您的结果 9 似乎假设引用彼此不同,例如在以下代码中:(
这确实 输出 9) 但通常情况并非如此参考类型。
If it's pass-by-reference (your original question was C but C doesn't have pass-by-reference and the question has changed since then anyway, so I'll answer generically), it's probably the case that
x
andy
will simply modify the variables that are passed in for them. That's what a reference is, after all.In this case, they're both a reference to the same variable
i
, so your sequence is likely to be:You can see this in operation with the following C (using pointers to emulate pass-by-reference):
Your result of 9 seems to be assuming that the references are distinct from one another, such as in the following code:
(this does output 9) but that's not usually the case with reference types.