没有return语句的函数的返回值是多少?

Him*_*ani 4 c return return-value function-call

#include<stdio.h>
int sel=5,out=10;

int findout(){
    if(sel==5)
        return out*=2;
}

int main(){
    int ret1,ret2=-1;
    ret1=findout();
    printf("before %d %d %d",sel,out,ret1);
    sel=8;out=7;
    ret2=findout();
    printf("\nafter %d %d %d",sel,out,ret2);
}
Run Code Online (Sandbox Code Playgroud)

输出:

在5 20 20之前

8 7 8之后

编辑:我的编译器没有显示任何警告.在这里你可以看到它.它在Ubuntu OS上的代码块GNU GCC编译器上

g++   -c Untitled1.cpp -o Untitled1.o
g++  -o Untitled1 Untitled1.o   
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,当我没有返回任何值(for sel=8out =7)时,值ret28多少?

pmg*_*pmg 12

什么时候sel不是5你的功能findout()不通过return声明.

那是非法的C; 并且你的编译器应该警告你.

不要忽略编译器警告.


Sou*_*osh 7

如果函数没有显式返回值(main()函数是异常),并且在调用者中使用返回值,则程序将调用未定义的行为.

引用C11,章节§6.9.1

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

在您的情况下,当if条件求值为false时,return控制路径中没有返回值的语句,并且您正在使用"预期"返回值,这将导致UB.