Say a function in C of boolean return type (boolean may be implemented as an enum of 0 and 1 or some other way, but that is not important):
boolean foo ()
{
//do something
return;
}
What does this return? does it return FALSE? or does it just exit from the function without any return? what will a function expecting a return from foo receive?
This is undefined behavior, a return statement without an expression shall only be used in a function whose return type is void. This is covered in the draft C99 standard section 6.8.6.4 The return statement:
[...]A return statement without an expression shall only appear in a function whose return type is void.
Interestingly this is an error by default when using clang but gcc without any flags seems to allow this code without even a warning. For gcc using the -std=c99 turns this into a warning and using the -pedantic-errors flag makes it an error.
A good set of flags to get used to using when compiling C programs using either gcc or clang would be the following:
-std=c99 -Wall -Wextra -Wconversion -pedantic
Adjusting the -std to the appropriate standard you are targeting.
According to the (draft) C99 standard, section 6.8.6.4 The return statement (paragraph 1):
A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.
So the code would be invalid.
Compiling this using GCC with -Wall throws an error:
warning: 'return' with no value, in function returning non-void [-Wreturn-type]
Although it compiles when not using -Wall and returns 1 (true), but I'm guessing this is GCC being nice (?).
(taken from WG14/N1256 Committee Draft — Septermber 7, 2007 ISO/IEC 9899:TC3)
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