返回值是多少?

发布于 2024-12-14 07:07:16 字数 211 浏览 2 评论 0原文

在通过引用传递参数的语言中,给定以下函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舂唻埖巳落 2024-12-21 07:07:16

如果它是按引用传递(你原来的问题是 C,但 C 没有按引用传递,而且问题从那时起就发生了变化,所以我会笼统地回答),情况可能是 xy 将简单地修改为它们传入的变量。毕竟,这就是参考。

在这种情况下,它们都是相同变量i的引用,所以你的序列可能是:

i = i + 1;       // i becomes 4.
i = i + 2;       // i becomes 6.
return i + i;    // return i + i, or 12.

你可以在使用以下 C 进行操作(使用指针模拟传递引用):

pax$ cat qq.c
#include <stdio.h>

int g(int *x, int *y) {
    *x = *x + 1;
    *y = *y + 2;
    return *x + *y;
}

int main (void) {
    int i = 3;
    int rv = g (&i, &i);
    printf ("Returned: %d\n", rv);
    return 0;
}

pax$ gcc -o qq qq.c ; ./qq
Returned: 12

您的结果 9 似乎假设引用彼此不同,例如在以下代码中:(

#include <stdio.h>

int g(int *x, int *y) {
    *x = *x + 1;
    *y = *y + 2;
    return *x + *y;
}

int main (void) {
    int i1 = 3, i2 = 3;
    int rv = g (&i1, &i2);
    printf ("Returned: %d\n", rv);
    return 0;
}

确实 输出 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 and y 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:

i = i + 1;       // i becomes 4.
i = i + 2;       // i becomes 6.
return i + i;    // return i + i, or 12.

You can see this in operation with the following C (using pointers to emulate pass-by-reference):

pax$ cat qq.c
#include <stdio.h>

int g(int *x, int *y) {
    *x = *x + 1;
    *y = *y + 2;
    return *x + *y;
}

int main (void) {
    int i = 3;
    int rv = g (&i, &i);
    printf ("Returned: %d\n", rv);
    return 0;
}

pax$ gcc -o qq qq.c ; ./qq
Returned: 12

Your result of 9 seems to be assuming that the references are distinct from one another, such as in the following code:

#include <stdio.h>

int g(int *x, int *y) {
    *x = *x + 1;
    *y = *y + 2;
    return *x + *y;
}

int main (void) {
    int i1 = 3, i2 = 3;
    int rv = g (&i1, &i2);
    printf ("Returned: %d\n", rv);
    return 0;
}

(this does output 9) but that's not usually the case with reference types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文