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

Why is main() a user defined function ?

When will I use void main() and int main()?


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.


Lundin is correct about C, but in C++ the wording is sufficiently distinct to make a difference:

[C++11: 3.6.1/1]: A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function.

[C++11: 3.6.1/2]: An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined [..]

The first bolded passage does not override or cancel out the second.

main returns int in C++, always.