C中的不稳定递归

时间:2013-04-14 09:11:44

标签: c recursion undefined-behavior

我在C和Java上运行此代码,分别得到65和55。我无法理解C如何获得65.请帮助。

int recur(int count) 
{
    if(count==10)
        return count;
    else
        return (count+recur(++count));
}

void main()
{
    printf("%d\n",recur(0));
}

2 个答案:

答案 0 :(得分:1)

return (count+recur(++count));

Undefined Behaviour。 在不同的编译器上,您可能会得到不同的结果,即使具有不同编译选项的相同编译器也可能导致不同的输出。

答案 1 :(得分:1)

使用一些调试语句重写代码并在codepad上进行测试可以显示正在发生的事情。我鼓励你采用这种方法运行代码,看看发生了什么。

int recur(int count) 
{
    int ret;
    if(count==10)
       ret = count;
    else {
       printf("Count Before = %d\n", count);
       ret =  (count +recur(++count));
    }
    printf("Count after = %d\n", ret);
    return ret; 
}

 void main()
 {
    printf("%d\n",recur(0));
 }

运行它给出了这个

Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 20
Count after = 29
Count after = 37
Count after = 44
Count after = 50
Count after = 55
Count after = 59
Count after = 62
Count after = 64
Count after = 65
65

所以你可以看到首先递增10,然后加10,然后9然后8等......

将其更改为i =(count + recur(count + 1))

给出

Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 19
Count after = 27
Count after = 34
Count after = 40
Count after = 45
Count after = 49
Count after = 52
Count after = 54
Count after = 55
Count after = 55
55

但是现在只达到10级嵌套,但增加的数量仍然是9。

IE中。预增量意味着您需要额外添加10。