What is the proper signature of the main
function in C++?
What is the correct return type, and what does it mean to return a value from main
?
What are the allowed parameter types, and what are their meanings?
Is this system-specific?
Have those rules changed over time?
What happens if I violate them?
Details on return values and their meaning
Per 3.6.1 ([basic.start.main]
):
A return statement in
main
has the effect of leaving themain
function (destroying any objects with automatic storage duration) and callingstd::exit
with the return value as the argument. If control reaches the end ofmain
without encountering areturn
statement, the effect is that of executingreturn 0;
The behavior of std::exit
is detailed in section 18.5 ([support.start.term]
), and describes the status code:
Finally, control is returned to the host environment. If status is zero or
EXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned. If status isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
The two valid mains are int main()
and int main(int, char*[])
. Any thing else may or may not compile. If main
doesn't explicitly return a value, 0 is implicitly returned.
From Standard docs., 3.6.1.2 Main Function,
It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { / ... / }
and
int main(int argc, char* argv[]) { / ... / }
In the latter form
argc
shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....
Hope that helps..
The exact wording of the latest published standard (C++14) is:
An implementation shall allow both
a function of
()
returningint
anda function of
(int
, pointer to pointer tochar)
returningint
as the type of
main
.
This makes it clear that alternative spellings are permitted so long as the type of main
is the type int()
or int(int, char**)
. So the following are also permitted:
int main(void)
auto main() -> int
int main ( )
signed int main()
typedef char **a; typedef int b, e; e main(b d, a c)
Source: Stackoverflow.com