main() arguments, was Re: typedef-ing an array

Brian Matthews 6sigma2 at polari.UUCP
Thu Jul 5 11:03:30 AEST 1990


In article <4241 at jato.Jpl.Nasa.Gov> kaleb at mars.UUCP (Kaleb Keithley) writes:
|void main () { exit(0); printf("I'll never be printed\n"); }

In general, trying an example that happens to work one way on one compiler
shouldn't be convincing.

In this case, proof (for ANSI C) would consist of quoting the standard
where it says "The exit function cannot return to its caller."

|3. We as software developers shouldn't be trying to anticipate what kind of
|code the compiler will generate.

Yes.  For one thing, we shouldn't assume that the compiler will generate
code for void main which works with a runtime that is calling int main.

Here's an example that may be more convincing.  Consider a machine where
it makes most sense to return values on the stack.  A compiler might
generate code that makes the stack look like the following for a call
to int main:

	sizeof (int) bytes for return value
	argc
	argv
	return address of code calling main

For a void function, it would generate code which expects a stack that
looks like:

	arg1
	arg2
	...
	argn
	return address

Now there's an obvious problem - void main (argc, argv) will look
for the stack:

	argc
	argv
	return address

so the code will use the random value reserved for the return value
as argc, and argc as argv.  If argv or argc are used, unexpected
results are fairly likely.

|-to write a portable program, you must not use this invisible third argument.
|Can you quote a reference to this assertion?

Assuming ANSI C again, we read in section 2.1.2.2:

"The function called at program startup is named main.  [...]  It can
be defined with no parameters [...] or with two parameters" and then
some verbiage on the two paremeters that basically says they must
work as argc and argv are expected to work.

Thus main must be declared with 0 or 2 arguments.  3 isn't 0 or 2, thus
main (argc, argv, envp) isn't a valid declaration of main and isn't
portable.
-- 
Brian L. Matthews	blm at 6sceng.UUCP



More information about the Comp.lang.c mailing list