164

Questions

  • 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?

Federico Baù
  • 6,013
  • 5
  • 30
  • 38
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • 2
    This is very closely related to, or a duplicate of, [What should `main` return in C and C++](http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c/18721336#18721336). – Jonathan Leffler May 17 '14 at 20:02
  • @JonathanLeffler No kidding... it was added to the list of duplicates in [revision 6](http://stackoverflow.com/revisions/204476/6) about 8 months ago. – fredoverflow May 18 '14 at 10:18

5 Answers5

206

The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

The name main is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

You can declare a function named main as a member function or in a namespace, but such a function would not be the main function that designates where the program starts.

The main function cannot be declared as static or inline. It also cannot be overloaded; there can be only one function named main in the global namespace.

The main function cannot be used in your program: you are not allowed to call the main function from anywhere in your code, nor are you allowed to take its address.

The return type of main must be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main with a return type of void; this is probably the most frequently violated rule concerning the main function).

There are two declarations of main that must be allowed:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

In (2), there are two parameters and they are conventionally named argc and argv, respectively. argv is a pointer to an array of C strings representing the arguments to the program. argc is the number of arguments in the argv array.

Usually, argv[0] contains the name of the program, but this is not always the case. argv[argc] is guaranteed to be a null pointer.

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:

int main(int argc, char* argv[])
int main(int argc, char** argv)

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

main() is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return statement in main(): if you let main() return without an explicit return statement, it's the same as if you had written return 0;. The following two main() functions have the same behavior:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined in <cstdlib> that can also be returned from main() to indicate success and failure, respectively.

The value returned by main() is passed to the exit() function, which terminates the program.

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main() function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 1
    IIRC the only guaranteed return values are 0, EXIT_SUCCESS (same effect as 0), and EXIT_FAILURE. EDIT: Ah, OK, other non-zero status values may be returned, but with implementation-defined meaning. Only EXIT_FAILURE is guaranteed to be interpreted in some way as a failure value. – Derrick Turk Nov 17 '10 at 17:24
  • It would not hurt to specify (just to be sure) that this is in reference to C++. Java/C# users may be confused since those languages actually *require* the entry point to—counterintuitively—be in a class (for some reason). Also, isn't the old `void main` format a holdover from C? – Synetech Dec 21 '10 at 20:24
  • 4
    @Synetech: The question asks in its first sentence, "What is the proper signature of the main function in C++?" and the question is tagged both [c++] and [c++-faq]. I can't help it if Java or C# users (or anyone else) are still confused. C# requires `Main` to be a static member function because it doesn't even have nonmember functions. Even C89 requires `main` to return `int`. I am not sufficiently familiar with K&R C to know its exact rules, but I would guess it also requires `main` to return `int` since `main` with no return type was somewhat common and no type = implicit `int` in K&R. – James McNellis Dec 21 '10 at 20:30
  • @ James McNellis can you please explain `why the return type of main should be int`? – Suhail Gupta Jun 15 '11 at 11:56
  • 3
    @Suhail: Because the language standard says the return type shall be `int`. – James McNellis Jun 15 '11 at 16:35
  • @ James McNellis Is there any harm if i use `void` ? – Suhail Gupta Jun 15 '11 at 18:06
  • 1
    @Suhail: Yes. Your code will not be correct C++ and many compilers will reject your code. – James McNellis Jun 15 '11 at 18:37
  • @ James McNellis Oh! thank you! Can you please name some compilers that will reject the `void` return type.I have only used `Visual studio c++` (and also the ancient turbo-c++ ) till now which passes my code. – Suhail Gupta Jun 15 '11 at 19:41
  • @ James McNellis How come **Microsoft's compiler** pass the code with `void` return type of `main` . **(microsoft visual c++ 2010 express edition)** – Suhail Gupta Jun 15 '11 at 19:45
  • 3
    @Suhail: Visual C++ permits a `void` return type [as a language extension](http://msdn.microsoft.com/en-us/library/6wd819wh.aspx). Compilers that do not permit it include GCC and Comeau. – James McNellis Jun 15 '11 at 21:08
  • Has the int main() {} version *always* been part of the standard or is it something that was added recently? – Chris Huang-Leaver Sep 21 '16 at 00:54
  • It was added to C more than fifty years ago, long before there was C++ standard. – arnt Nov 08 '17 at 11:14
  • On less-common platforms (e.g., VAX/VMS), with compilers that followed very old versions of the then-more-ambiguous C standard, `EXIT_SUCCESS` and `EXIT_FAILURE` were only reliable as arguments to `exit()`. Returning either of them from `main()` could have unintended effects. Now that the standard has been clarified, there's no standard, portable way to return a completely arbitrary value to the host environment; you'd have to use a host-specific extension. – Adrian McCarthy Mar 15 '19 at 20:51
15

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..

liaK
  • 11,422
  • 11
  • 48
  • 73
  • 2
    is there any specific reason as to why the return type of `main` should be `int` ? – Suhail Gupta Jun 15 '11 at 12:01
  • 1
    @SuhailGupta: So that the calling process knows whether _this_ process should be deemed successful or not. Allowing `void` breaks that model. It doesn't even really make sense if you had it mean "always deem success". Because you had no way of saying if the process actually failed, so did you _really_ succeed? No, return `int`. – Lightness Races in Orbit Jan 02 '17 at 13:55
3

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.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
stonemetal
  • 6,111
  • 23
  • 25
  • 1
    I have never seen code not getting compiled when i mention the return type of `main` to be void. **Is there any specific reason that return type of main should be int ?** – Suhail Gupta Jun 15 '11 at 12:03
  • 4
    The language specification says main must have a return type of int. Any other return type allowed by your compiler is a compiler specific enhancement. Basically using void means you are programming in a language similar to but not C++. – stonemetal Jun 15 '11 at 23:33
  • 2
    The reason the standard requires an `int` as the return type of `main` is that this value is handed to the shell as the program's exit code, and `sh` expects an `int`. – uckelman Jul 12 '13 at 11:55
  • Maybe the reason is discipline? There can be more than one path out. If the return type is `void` they are all silent. With `int` we have to define the specific exit-value for each return from `main`. – Andreas Spindler Oct 30 '18 at 08:04
3

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

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)
M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    NB. I posted this answer as in comments to another thread, someone tried to cite this thread as evidence that `int main(void)` was not correct in C++. – M.M Jul 01 '17 at 09:22
  • 4
    @Stargateur `auto main() -> int` does not have a deduced return type. Pay attention to the { in "(auto main() {... is not allowed)" and please learn to know when you don't yet know enough to add anything meaningful. –  Jul 01 '17 at 09:44
2

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 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 is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720