简体   繁体   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);
    }

why is 5 getting printed when it is not even mentioned what to return? 为什么什至没有提到要退还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);
    }

and this one is returning 2. which is the first value of i when the loop breaks due to return statement. 并且此函数返回2。这是由于return语句导致循环中断时i的第一个值。 but where is it mentioned that the function has to return i ?? 但是在哪里提到该函数必须返回i ??

Code executed in Linux. 在Linux中执行的代码。

Not returning a value from a function designed to return an int invokes Undefined Behavior . 不从旨在返回int的函数中返回值将调用Undefined Behavior Anything can happen. 什么都可能发生。 Quote from the C11 standard: 引用C11标准:

6.9.1 Function definitions 6.9.1函数定义

[...] [...]

  1. If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. 如果到达终止函数的} ,并且调用者使用了函数调用的值,则该行为未定义。

You're not returning an Integer in a method designed to return an Integer, there must be a catch that is returning the last integer created. 您不是在设计用于返回Integer的方法中返回Integer的,而必须有一个catch返回了所创建的最后一个整数。

If you don't want to return anything, simply return void. 如果您不想返回任何东西,只需返回void。

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

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