What is the return value from a function without a return statement?

#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);
}

Output:

up to 5 20 20

after 8 7 8

EDIT . My compiler does not show any warnings. Here you can see it. Its codeblock compiler GNU GCC on Ubuntu OS

g++   -c /home/himani/Untitled1.cpp -o /home/himani/Untitled1.o
g++  -o /home/himani/Untitled1 /home/himani/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))

Here, in the second case, when I do not return any value (for sel=8and out =7), how is it value ret2: 8?

+4
source share
3 answers

When selnot 5, your function findout()does not go through the instruction return.

It is illegal C; and your compiler should warn you about this.

.

+12

(main() ) , undefined.

C11, §6.9.1

}, , , undefined.

, if false, return, , , UB.

+7

. 8. , , Clang:

clang-3.5 main.cpp
main.cpp:6:1: warning: control may reach end of non-void function [-Wreturn-type]

:

./a.out 
Illegal instruction (core dumped)
+4

Source: https://habr.com/ru/post/1652877/


All Articles