繁体   English   中英

从int返回函数不返回任何内容时,c中出现意外输出

[英]unexpected output in c while returning nothing from an int returning function

    #include <stdio.h>

    int foo(int a)
    {
        int i;
        for(i=2;i<=a;i++)
        {
            if(i%5==0)
            {
                return;
            }
        }
    }

    int main()
    {
        int c = foo(10);
        printf("%d",c);
    }

为什么什至没有提到要退还5时打印?

   #include <stdio.h>

    int foo(int a)
    {
        int i;
        for(i=2;i<=a;i++)
        {
            return; //no variable is attached with return
        }
    }
    int main()
    {
        int c = foo(10);
        printf("%d",c);
    }

并且此函数返回2。这是由于return语句导致循环中断时i的第一个值。 但是在哪里提到该函数必须返回i ??

在Linux中执行的代码。

不从旨在返回int的函数中返回值将调用Undefined Behavior 什么都可能发生。 引用C11标准:

6.9.1函数定义

[...]

  1. 如果到达终止函数的} ,并且调用者使用了函数调用的值,则该行为未定义。

您不是在设计用于返回Integer的方法中返回Integer的,而必须有一个catch返回了所创建的最后一个整数。

如果您不想返回任何东西,只需返回void。

暂无
暂无

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

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