我遇到了以下问题:
#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.
意思是,虽然这次这个逻辑通过了,但下次我可能不会这样,或者如果你自己运行它。