c中的意外输出,而int返回函数没有返回任何内容

时间:2015-05-30 12:02:05

标签: c

    #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中执行的代码。

2 个答案:

答案 0 :(得分:4)

不从用于返回int的函数返回值调用Undefined Behavior。任何事情都可能发生。引用C11标准:

  

6.9.1功能定义

     

[...]

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

答案 1 :(得分:0)

你没有在一个设计用于返回Integer的方法中返回一个Integer,必须有一个catch返回创建的最后一个整数。

如果您不想返回任何内容,只需返回void。