用户定义函数的意外返回值

时间:2014-02-01 18:02:52

标签: c++

#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,但我不知道为什么。任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

这里有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 * 1 = 6561

这是因为函数是在实际乘法发生之前计算的,但是当堆栈展开时,在每次乘法时,x通过引用传递已经是它的最后一个值,即9