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?
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.
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.
If there are no explicit returns from a function, the value of the last evaluated expression is returned automatically in R.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With