用户定义的功能的意外返回值

Unexpected returned value of a user defined function

本文关键字:返回值 意外 功能 用户 定义      更新时间:2023-10-16
#include <iostream.h>
int someFunction(int &x, int c) {
    c=c-1;
    if(c==0) {
        return 1;
    }
    x=x+1;
    return someFunction(x,c) * x;
}
void main() {
    int p = 5;
    cout << someFunction(p,p);
}

此代码返回6561,但我不知道为什么。谁能帮助我?

您在这里有5个迭代:

1st iteration - C is 5 and reduced by 1 -> c=4 which is not 0 so we go on to "(++x) * someFunc".
2nd iteration - C is 4 and reduced by 1 -> c=3 which is not 0 so we go on to "(++x) * someFunc".
3rd iteration - C is 3 and reduced by 1 -> c=2 which is not 0 so we go on to "(++x) * someFunc".
4th iteration - C is 2 and reduced by 1 -> c=1 which is not 0 so we go on to "(++x) * someFunc".
5th iteration - C is 1 and reduced by 1 -> c=0 so we return 1.

在这一点上,我们有x * x * x * x * 1,在4个增量x = 9之后,因此值为9 * 9 * 9 * 9 * 9 * 1 = 6561

这是因为在发生实际乘法之前对函数进行评估,但是随着堆栈的放松,在每次乘法的时刻,通过参考传递的x已经在其最后一个值中,即9。