【问题标题】:Extra 444 returned while calling main function recursively?递归调用main函数时返回额外的444?
【发布时间】:2020-10-17 22:28:14
【问题描述】:
#include<stdio.h>
int main()
{
    static int s;
    ++s;
    printf("%d",s);
    if(s<=3)
        main();
    printf("%d",s);

}

我得到了输出12344444,但只需要12344。谁能解释一下为什么会出现这个问题并提供解决方案?

【问题讨论】:

  • 最后一个printf 语句将在递归展开时执行多次。毕竟,您多次致电main
  • 调用 main() 不是未定义的行为吗?
  • 递归调用main其实是违法的。
  • @john 仅在 C++? C 标准没有提到这一点。
  • @John - 不正确,尽管在 C++ 中就是这种情况。这两种语言之间的另一个区别。

标签: c recursion static main


【解决方案1】:
#include<stdio.h>
int main()
{
    static int s;
    ++s;
    printf("%d",s); // this printf is called and will print each
                    // number as the recursion is called down
    if(s<=3)
        main();
    printf("%d",s); // <<-- this is why
                    // this one is called as the recursion functions
                    // return so it will be called with the highest 
                    // number as many times as there were recursion.

}

要得到你想要的尝试

  #include<stdio.h>
    void recursive()
    {
        static int s;
        ++s;
        printf("%d",s); // this printf is called and will print each
                        // number as the recursion is called down
        if(s<=3)
            recursive();
        else 
            printf("%d",s); // call only if s > 3 
    
    }

    int main()
    {
       recursive();
    }

【讨论】:

  • 实际上,当遇到第二个printf 语句时,s 的值将总是 > 3。您的评论应该说的是“只有在没有递归发生时才调用”。
  • 我很感激。但是 OP 的问题是打印了三个额外的 4 值。
  • @TedLyngmo 这可能是不明智的,但在 C 中并不违法。它的合法性在“5.1.2.2.3 程序终止 1 如果主函数的返回类型是与int兼容的类型,返回从初始调用到main函数相当于调用exit函数。”
  • @WeatherVane 正确 - 我已删除我的评论并为你的评论点赞。我刚刚浏览了当前的 C 标准,发现根本不支持我的声明。
  • @WeatherVane 不,你的评论非常好,为我这样的人(他们认为它非法)节省了很多时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 2017-04-09
相关资源
最近更新 更多