Why is the type of the main function in C and c++ left to the user to define? [duplicate]

EDIT This answer is not as complete as it could be since it doesn’t really address the strange sentence “or otherwise in some implementation-defined manner”. I have now written a more complete answer which also addresses C90, C11 and C++. END OF EDIT

Here is what the C standard says (ISO C 9899:1999):

5.1.2.1 Freestanding environment

In a freestanding environment (in
which C
program execution may take place
without any benefit of an operating
system), the name and type of the
function called at program startup are
implementation-defined.
/ .. /
The effect
of program termination in a
freestanding environment is
implementation-defined.

5.1.2.2 Hosted environment

A hosted environment need not be provided, but
shall conform to the following
specifications if present.

5.1.2.2.1 Program startup

The function called at program startup is named
main. The implementation declares no
prototype for this function. It shall
be defined with a return type of int
and with no parameters:

int main(void) { /* … */ }

or with two parameters (referred to
here as argc and argv, though any
names may be used, as they are local
to the function in which they are
declared):

int main(int argc, char* argv[]) { /*
… */ }

The text in the C++ standard is more or less identical. Please note that “Program startup” in the text is a subclause to hosted environment.

This means:

  • If your program is running in a hostless environment (your program is an embedded system or an operative system), it may have any return type. void main() is most common.

  • If your program is running in a hosted environment (on top of an OS), main() must return int, and may have additional parameters.

Leave a Comment