C语言 递归如何在没有额外return语句的情况下工作?

mbskvtky  于 2024-01-06  发布在  其他
关注(0)|答案(1)|浏览(135)

此问题在此处已有答案

Why does flowing off the end of a non-void function without returning a value not produce a compiler error?(11个回答)
If a function returns no value, with a valid return type, is it okay to for the compiler to return garbage?(4个答案)
Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?(2个答案)
3天前关闭。
有谁能解释一下下面这段代码的结果吗?下面是递归函数。结果应该是:5*6*7*8*9*10 == 151200但是结果显示4*5*6*7*8*9*10 == 604800现在4是从哪里来的?如果你用递归树解释会更好。

#include <stdio.h>
#include <string.h>
int fun(int a)
{
    if (a > 4)
    {
        return fun(a - 1) * a;
    }
}
int main()

{
    int x = fun(10);
    printf("%d", x);
}

字符串

h9a6wy2h

h9a6wy2h1#

它不起作用。它是未定义的行为,你的程序可以以任何方式运行。

<source>: In function 'fun':
<source>:15:1: warning: control reaches end of non-void function [-Wreturn-type]
   15 | }
      | ^

字符串
你的编译器 * 应该 * 警告你(它不会,因为你需要启用额外的警告,我建议-Wall -Wextra + -Werror),你应该在所有函数执行路径上有return语句。

int fun(int a)
{
    if (a > 4)
    {
        return fun(a - 1) * a;
    }
    return 1;
}


那么4是从哪里来的呢?如果你用递归树来解释会更好。
它只是一个未指定的值,因为它是未定义的行为,函数返回的值可以是任何东西。
例如,clang编译器生成打印***0***的代码
https://godbolt.org/z/z6nYY4rhf
带-Os的gcc * 4198464 *
https://godbolt.org/z/j7fEebPKP

相关问题