简体   繁体   English

如何在 C 编程中跟踪递归?

[英]How can I trace recursion in C programming?

I was trying to trace the recursion.我试图追踪递归。 In my logic answer should be 30, but the answer is 36. My question is how to trace this recursion?在我的逻辑中答案应该是 30,但答案是 36。我的问题是如何追踪这个递归?

#include<stdio.h>
int fun(int n)
{
    int static x=0;
    if(n>=0)
    {
        x=x+1;
        return(fun(n-1)+x);
    }
    return 0;
}

int main()
{
    int a=5;
    printf("%d",fun(a));    
}

If you are not used to using a debugger, it's probably a good time to start using one.如果您不习惯使用调试器,那么现在可能是开始使用调试器的好时机。

Until then, you could add printouts to see what your program is doing:在那之前,您可以添加打印输出以查看您的程序在做什么:

#include <stdio.h>

int fun(int n) {
    printf("n=%d\n", n);
    int static x = 0;
    if (n >= 0) {
        x = x + 1;        
        int res = fun(n - 1);
        printf("returning fun(%d)\t%d + %d = %d\n", n - 1, res, x, res + x);
        return res + x;
    }
    printf("termination point reached, x = %d\n", x);
    return 0;
}

int main() {
    int a = 5;
    printf("%d\n", fun(a));
}

Output: Output:

n=5
n=4
n=3
n=2
n=1
n=0
n=-1
termination point reached, x = 6
returning fun(-1)   0 + 6 = 6
returning fun(0)    6 + 6 = 12
returning fun(1)    12 + 6 = 18
returning fun(2)    18 + 6 = 24
returning fun(3)    24 + 6 = 30
returning fun(4)    30 + 6 = 36
36

Your function has undefined behavior because evaluations of the operands in the addition expression in the return statement您的 function 具有未定义的行为,因为在 return 语句中的加法表达式中计算操作数

return(fun(n-1)+x);

are unsequenced.是无序的。 That is the value of x in the first call of the function can be evaluated before the next recursive call of the function.也就是说,在 function 的下一次递归调用之前,可以评估第一次调用 function 中的x值。 In this case x will be equal to 1 .在这种情况下x将等于1 If the value of x will be evaluated after the next recursive call of the function it can have another value because the variable x has static storage duration.如果在下一次递归调用 function 之后评估x的值,它可以有另一个值,因为变量x具有 static 存储持续时间。

From the C Standard (6.5 Expressions)来自 C 标准(6.5 表达式)

2 If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. 2 如果标量 object 上的副作用相对于相同标量 object 上的不同副作用或使用相同标量 ZA8CFDE6331BD59EB2AC966F8911C4B 的值的值计算未排序,则行为未定义。 If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.如果表达式的子表达式有多个允许的排序,则如果在任何排序中出现这种未排序的副作用,则行为未定义。

So in different compilers you can get different results depending on how the compilers generate the object code.因此,在不同的编译器中,您可以获得不同的结果,具体取决于编译器如何生成 object 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM