What is the proper declaration of main in C++? [duplicate]
Asked Answered
A

5

166

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?

Accomplishment answered 17/11, 2010 at 17:12 Comment(2)
@JonathanLeffler No kidding... it was added to the list of duplicates in revision 6 about 8 months ago.Accomplishment
This question is not an exact duplicate of the What should main() return in C and C++?. However, everything that it asks is already answered over there in greater detail and in greater quality, which makes this question a duplicate. This question is also problematic in its current state because it's not very focused, and is asking about system-specifics, historical changes, and all sorts of things just to forcefully distinguish itself. This in itself might warrant a "needs focus" close reason.Addington
M
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.

Minter answered 17/11, 2010 at 17:19 Comment(13)
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.Dalmatia
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?Chastise
@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.Minter
@ James McNellis can you please explain why the return type of main should be int?Chap
@Suhail: Because the language standard says the return type shall be int.Minter
@ James McNellis Is there any harm if i use void ?Chap
@Suhail: Yes. Your code will not be correct C++ and many compilers will reject your code.Minter
@ 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.Chap
@ James McNellis How come Microsoft's compiler pass the code with void return type of main . (microsoft visual c++ 2010 express edition)Chap
@Suhail: Visual C++ permits a void return type as a language extension. Compilers that do not permit it include GCC and Comeau.Minter
Has the int main() {} version always been part of the standard or is it something that was added recently?Clavicembalo
It was added to C more than fifty years ago, long before there was C++ standard.Alephnull
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.Hallux
H
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..

Hollinger answered 18/11, 2010 at 5:21 Comment(2)
is there any specific reason as to why the return type of main should be int ?Chap
@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.Gilburt
E
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.

Enkindle answered 17/11, 2010 at 17:49 Comment(4)
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 ?Chap
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++.Enkindle
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.Theodicy
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.Pupil
T
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)
Turtleback answered 1/7, 2017 at 9:22 Comment(3)
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++.Turtleback
@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.Absquatulate
bullet #5 got a chuckle out of me...reminds me of the DIKUMUD era of my programming. TypeDef a TypeDef to define a TypeDef ;)Reynaldoreynard
W
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.

Wivina answered 2/1, 2012 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.