I am just starting out in C++ and we are learning about typical statements in code. One that we typically use is int main()
at the start of the actual program portion. I understand we can also use void main()
.
My question is, why do we use int
? I thought this was for defining variable types. Are we actually declaring that the whole code is a variable?
The main
function (which is your entry point to the program) is defined by the C++ standard to always return int
. void main
is not valid according to the standard (even if your compiler accepts it).
The purpose of the int
return value is to return a value to the operating system, telling it whether your program completed successfully or not. There are two well-defined macros available for returning such a value that you can depend on having a sane meaning - they are EXIT_SUCCESS
and EXIT_FAILURE
. You can return other values than those, but only those are guaranteed to have a sane semantic meaning - any other value is going to be platform/OS dependent (and while EXIT_SUCCESS
is usually zero, you can't depend on that - on VMS (for example) that is not true, so you really should use the macros in portable code - and regardless, return EXIT_SUCCESS;
communicates meaning much clearer than return 0;
).
main
is special compared to all other functions though, in that if no value is explicitly returned it implicitly returns EXIT_SUCCESS
- I personally don't like relying on that though; I prefer explicitly returning what I intend to return.