Must main return a value?

Michael Henning michi at ptcburp.ptcbu.oz.au
Fri Jun 28 14:33:42 AEST 1991


walterm at hpwrce.HP.COM (Walter Murray) writes:

>Is the following program strictly conforming?

>   int main(void) { return; }

>Many people have written that the main function must return a value.
>I can't find such a requirement in the Standard.  I have read 2.1.2.2.3
>and 3.6.6.4.  Am I missing something?

Section 2.1.2.2.3 (Program termination) is quite explicit:

"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. If the main function executes a return that specifies no
value, the termination status returned to the host environment is undefined."

Section 3.6.6.4 (The return Statement) says:

"If a return statement without an expression is executed, and the value of
the function call is used by the caller, the behavior is undefined."

Note that for section 3.6.6.4 to apply, there must be a caller, but the
caller in this case is the environment, so 2.1.2.2.3 applies instead.

The upshot is that the program is strictly conforming, but the exit
status the OS gets to see is undefined.

To write truly portable code, it pays to explicitely call exit() since
some (non-conforming) implementations to not return a defined value
to the OS when a return from main is executed (even if that return
specifies a value). So it pays to write

int main(void) { exit(0); }

to be sure. Unfortunately, many versions of lint will complain about
an undefined return value from main in this case, because they do not
know about exit(). If you want to be paranoid, you can write

int main(void)
{
	exit(0);
	return 0;	/* Keep lint happy */
}


						Michi.
-- 
      -m------- Michael Henning			+61 75 950255
    ---mmm----- Pyramid Technology		+61 75 522475 FAX
  -----mmmmm--- Research Park, Bond University	michi at ptcburp.ptcbu.oz.au
-------mmmmmmm- Gold Coast, Q 4229, AUSTRALIA	uunet!munnari!ptcburp.oz!michi



More information about the Comp.std.c mailing list