Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function defined as int but having no return statement in the body still compiles

Tags:

c

compilation

Say you have a C code like this:

#include <stdio.h>

int main(){
    printf("Hello, world!\n");
    printf("%d\n", f());    
}

int f(){

}

It compiles fine with gcc, and the output (on my system) is:

Hello, world!

14

But.. but.. how is that possible? I thought that C won't let you compile something like that because f() doesn't have a return statement returning an integer. Why is that allowed? Is it a C feature or compiler omission, and where did 14 come from?

like image 362
Nikita Avatar asked Nov 23 '10 19:11

Nikita


People also ask

What happens if there is no return statement in C?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Can a function not have a return statement?

A function without an explicit return statement returns None . In the case of no arguments and no return value, the definition is very simple. Calling the function is performed by using the call operator () after the name of the function.

What will be returned by a function if you don't include a return statement in R?

If there are no explicit returns from a function, the value of the last evaluated expression is returned automatically in R.

Which function must not use a return statement?

In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.


2 Answers

The return value in this case, depending on the exact platform, will likely be whatever random value happened to be left in the return register (e.g. EAX on x86) at the assembly level. Not explicitly returning a value is allowed, but gives an undefined value.

In this case, the 14 is the return value from printf.

like image 172
Adam Vandenberg Avatar answered Oct 02 '22 07:10

Adam Vandenberg


compile with -Wall to enable more sanity checking in the compiler.

gcc -Wall /tmp/a.c
/tmp/a.c: In function ‘main’:
/tmp/a.c:5: warning: implicit declaration of function ‘f’
/tmp/a.c:6: warning: control reaches end of non-void function
/tmp/a.c: In function ‘f’:
/tmp/a.c:10: warning: control reaches end of non-void function

Note how it flags up the missing return statements - as "control reaches end of non-void function"?

Always compile using -Wall or similar - you will save yourself heartache later on.


I can recall several occasions when this exact issue has caused hours or days of debugging to fix - it sorta works until it doesn't one day.

like image 42
Alex Brown Avatar answered Oct 02 '22 07:10

Alex Brown