Concerning non-void functions without a return statement, the
C99 standard says (and it seems that C11 is identical):
5.1.2.2 Hosted environment
5.1.2.2.3 Program termination
1 If the return type of the main function is a type compatible
with int, a return from the initial call to the main function
is equivalent to calling the exit function with the value
returned by the main function as its argument;10) reaching
the } that terminates the main function returns a value of 0.
If the return type is not compatible with int, the termination
status returned to the host environment is unspecified.
6.9.1 Function definitions
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.
I can see 3 cases for hosted environments:
1. The initial call of the main function.
2. The other calls of the main function (when declared as returning
an int).
3. The other function calls.
Cases 1 and 3 are clearly specified. But case 2 is ambiguous. First,
6.9.1p12 doesn't exclude the main() function (it doesn't exclude it
either for case 1, but the caller being outside of the C environment
in this case, I don't see a contradiction with 5.1.2.2.3p1); that
would mean that the behavior is undefined if the value is used (see
an example below). 5.1.2.2.3p1 says that the main function returns
a value of 0, but this is not clear whether this applies to all the
calls to main, or only to the initial one. Based on 6.9.1p12 (which
doesn't exclude main), the fact that this specific rule for main is
under a section named "Program termination" and the fact that both
parts of the sentence are separated by a semi-colon (keeping the
context of the first part), I would say that it applies only for
the initial call (i.e. at program termination). But GCC 4.4 to 4.7
invoked with -std=c99 -Wreturn-type doesn't give a warning. What do
you think about this?
The example:
#include <stdio.h>
static int i = 0;
int main (void)
{
if (i++ == 0)
printf ("%d\n", main ());
}
The question is whether there is an undefined behavior (in which case
GCC should have given a warning) or this program should necessarily
output 0.
--
Vincent Lefèvre <
vin...@vinc17.net> - Web: <
http://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <
http://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)