Reputation: 788
Reading C11 Standard, when speaking about main()
I read:
5.1.2.2.1 "...[main] shall be defined with a return type of int".
5.1.2.2.3 "...If the return type is not compatible with int,..."
The latter suggest that I can define main()
to return a non integer value.
How is it possible if main "shall" return int?
And also, "The implementation declares no prototype for this function" gives freedom to use a non-integer return type?
Why immediately after says: "[main] shall be defined with a return type of int"?
Upvotes: 2
Views: 460
Reputation: 78903
I have the impression that the sentence
or in some other implementation-defined manner.
leads to confusion here. implementation-defined is the C standard jargon for defined and documented by the compiler provider. This doesn't mean that the programmer is free to chose an arbitrary prototype for main
. It means that he may use a different prototype if his compiler documentation foresees it.
The only other platform specific return type I know of is void
, which is allowed on some oldish platforms. For the arguments to main
, I know of platforms that allow for a third parameter that passes a pointer to the environment.
Upvotes: 4
Reputation: 239861
The implementation declares no prototype for this function.
That is, there's no existing prototype; whether you define it as int main(void)
, int main (int argc, char *argv[])
, or in "some other implementation-defined manner", you won't be conflicting with some implicit prototype.
or in some other implementation-defined manner.
If we read this as governing the return type as well, then there's no conflict with what comes later, because this basically says that the signature of main
can be whatever you like, if it makes sense for the implementation — and later — but, if main
returns int
or something convertible to int
then returning from main
has to be equivalent to calling exit
(since exit
is declared void exit(int)
).
One possible point against my reading, though, is that if this was the intent I would expect it to say that the behavior when the return type is not int
is implementation-defined, rather than undefined.
Upvotes: 1
Reputation: 360662
The full quote says If the return type is not compatible with int, the termination status returned to the host environment is unspecified.
That means it's undefined behavior. When main()
exits, the program is essentially terminating, and the return value of main will be used as the exit status of the program. Since on most systems programs can only return an integer as their exit status, the return value of main is used as that exit code. Returning a string or pointer or whatever means you're returning something that the calling environment can't deal with.
Upvotes: 2