c++ - C++中引用变量的使用

标签 c++ recursion reference pass-by-reference

<分区>

我遇到了以下问题:

#include <stdio.h>

int f(int &x, int c)
{
    c  = c - 1;
    if (c == 0) return 1;
    x = x + 1;
    return f(x, c) * x;
}
int main()
{
    int p = 5;
    printf("%d", f(p, p));
}

据我所知,递归调用应该有效,并且每次递归调用时,c 的值应减少 1,x 的值应增加 1。但是,如果我这样计算,答案是 3024。但是,在执行时,输出结果是 6561。我不太确定这个答案是怎么来的。

我有指向提出这个问题的文章的链接,但我不明白 x 如何保持不变,如此链接中所述:https://www.geeksforgeeks.org/c-references-question-1/

有人可以帮我处理这段代码背后的工作吗?

最佳答案

可能有任何结果,由于Undefined behavior .

由于 x 是通过引用传递的,所以最后的赋值很重要。因此,我们有:

9*9*9*9*1=6561

我们延迟对 f(x, c) * x 的计算,所有后续的递归调用都可以访问 x。我们以这种方式增加 x 直到 c 等于 0,这意味着我们将 x 增加到它为 9

当我们遇到基本情况时(c == 0),当前调用返回 1,而 x 已经是 9

然后我们计算乘法 1 * x * x * x * x,其中 x 等于 9。因此,6561

完美的解释? 没那么多

有趣的是,在 C++ 中没有从左到右或从右到左求值的概念:

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

意思是,虽然这次这个逻辑通过了,但下次我可能不会这样,或者如果你自己运行它。

关于c++ - C++中引用变量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68177809/

相关文章:

performance - perl 中的哈希元素的别名

javascript - 替换对象并保留指向该对象的现有指针

c++ - 具有 `stdio.h` 函数的模板和名称查找

c++ - openCV 中的结果 compareHist

python - 这个嵌套递归怎么理解呢?

python - 如何递归替换元组对列表?

c++ - 引用结构中的C++内存管理

c++ - 如何使用与错误报告无关的区域设置 strtod

c++ - 如何使用这个宏来测试内存是否对齐?

javascript - 用于递归函数的 Webworker