Implicit int return value of C function
From the '89 standard as quoted in the new testament:
Flowing off the end of a function is equivalent to a return with no expression. In either case, the return value is undefined.
That standard usually expresses the on-the-ground behavior of pre-existing implementations.
The return statement is never mandatory at the end of a function, even if the function return type is not void
. No diagnostic is required and it is not undefined behavior.
Example (defined behavior):
int foo(void)
{
}
int main()
{
foo();
}
But reading the return value of foo
is undefined behavior:
int bla = foo(); // undefined behavior
From the C Standard:
(C99, 6.9.1 on p.12) "If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined."
The main
function is an exception to this rule as if the }
is reached in main
it is equivalent as if there was a return 0;
statement.
(C99 draft, 5.1.2.2.3 on p.13) ...reaching the
}
that terminates themain
function returns a value of 0.
Such a thing is possible, but only under the assumption that the return value of the function is never used. The C11 standard says in para 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.
(AFAIR previous version of the standard had similar wording)
So it would be a good idea to transform all the functions of that sort that you have to void
functions, so no user of such a function could be tempted to use the return value.