Why is it "int main()" and not "void main()"?
Because the language standard says so.
Why does it say so? Because many operating systems use the status returned by the main program, and because in C the void
type and keyword wasn’t even introduced until the language had been in use for a number of years, and there was no particular reason to change it when void
was introduced.
C and C++ are two different languages.
In C, main
can be defined as:
int main(void) { /* … */ }
or
int main(int argc, int *argv[]) { /* … */ }
or equivalent, or in some other implementation-defined way. So a compiler can accept void main()
, but it’s not required to — and there’s no good reason not to use one of the standard forms.
For C++, it’s mostly the same — except that the parameterless form is
int main() { /* … */ }
though C++ allows (void)
for compatibility with C. (Empty parentheses have a different meaning in C++ than in C). C++ also allows other implementation-defined forms — but the return type must be int
.
(All this is for hosted implementations. For freestanding implementations, typically for targets with no operating system, the program entry point is implementation-defined, and might not even be called main
.)