4
#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:

before 5 20 20

after 8 7 8

EDIT: My compiler doesn't show any warnings.Here you can see it. Its on codeblocks GNU GCC compiler on Ubuntu OS

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))

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

Community
  • 1
  • 1

3 Answers3

12

When sel is not 5 your function findout() does not go through a return statement.

That is illegal C; and your compiler should warn you about it.

Do not ignore your compiler warnings.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • Historical note: before there was a standard C, there wasn't a `void` type, so functions that nominally returned `int` but didn't need to return a value used `return` with no value or dropped off the end of the function and there was no problem as long as the calling code did not attempt to use the 'return value'. When C was standardized,, existing code could not be invalidated. However, in all variants of C, sometimes returning a value and sometimes not returning a value was a very bad idea. – Jonathan Leffler Aug 29 '16 at 15:43
  • I am using GNU GCC compiler on Ubuntu OS. It doesn't show any warnings. Moreover i tried on online Ide it gave the same result. – Himani Virmani Aug 29 '16 at 16:57
  • @HimaniVirmani: you need to enable warnings. Try `gcc -std=c99 -pedantic -Wall -Wextra source.c` for a good set of enabled warnings. – pmg Aug 30 '16 at 08:08
7

In case a function does not return a value explicitly (main() function is an exception), and the return value is used in caller, the program invokes undefined behavior.

Quoting C11, chapter §6.9.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.

In you case, when the if condition evaluates to false, there's no return statement in the control path that returns a value, and you're using the "expected" returned value, which causes the UB.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

It's undefined behavior. For your compiler the result is 8. But for example after compile with Clang:

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

And when running:

./a.out 
Illegal instruction (core dumped)
klutt
  • 30,332
  • 17
  • 55
  • 95
j2ko
  • 2,479
  • 1
  • 16
  • 29