gpt4 book ai didi

pass-by-reference - 当我们在此函数中按值传递结果时会发生什么?

转载 作者:行者123 更新时间:2023-12-05 04:00:45 26 4
gpt4 key购买 nike

考虑这段代码。

foo(int x, int y){
x = y + 1;
y = 10;
x++;
}
int n = 5;
foo(n,n);
print(n);

如果我们假设该语言支持按值传递结果,答案会是什么?据我所知,按值传递结果复制进出。但是我不确定将 n 复制到两个不同的形式参数时的值是多少。 xy 应该像引用一样吗?或者 n 是否应该根据最后复制的值获取 xy 的值?

谢谢

最佳答案

无论是普通的传值还是传值结果,xy都会变成单独的副本 of n,除了它们以相同的值开头之外,它们之间没有任何联系。

但是,按值传递结果在函数退出时将值分配回原始变量,这意味着 n 将采用 xy哪个第一个(或者,更重要的是,最后一个,因为这将是它的最终值)是开放的解释,因为您没有指定您实际使用的语言。

The Wikipedia page on this entry关于这个主题有这样的说法(“call-by-copy-restore”是您所问内容的术语,我强调了重要的一点并进行了解释以使其更清楚):

The semantics of call-by-copy-restore also differ from those of call-by-reference where two or more function arguments alias one another; that is, point to the same variable in the caller's environment.

Under call-by-reference, writing to one will affect the other immediately; call-by-copy-restore avoids this by giving the function distinct copies, but leaves the result in the caller's environment undefined depending on which of the aliased arguments is copied back first. Will the copies be made in left-to-right order both on entry and on return?

希望语言规范能够阐明实际一致的行为,以避免您在 C 和 C++ 中经常看到的所有未定义行为角落:-)

检查下面的代码,对您的原始代码稍作修改,因为我天生懒惰,不想计算最终值:-)

foo(int x, int y){
x = 7;
y = 42;
}
int n = 5;
foo(n,n);
print(n);

我认为最有可能的直接可能性是:

  • 退出时严格从左到右复制,n 将变为 x 然后是 y,所以 42 .
  • 退出时严格从右到左复制,n 将变为 y 然后是 x,所以 7 .
  • 未定义的行为,n 可以取任一个,也可能取任何值。
  • 编译器提出诊断并拒绝编译,如果它没有严格的规则并且不希望您的代码以(看似)随机的方式结束。

关于pass-by-reference - 当我们在此函数中按值传递结果时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com