patterncppCritical
What should main() return in C and C++?
Viewed 0 times
returnshouldandmainwhat
Problem
What is the correct (most efficient) way to define the
If
main() function in C and C++ — int main() or void main() — and why? And how about the arguments?If
int main() then return 1 or return 0?Solution
The return value for
and
which is equivalent to
It is also worth noting that in C++,
Efficiency is not an issue with the
You find the C++ specifications in [basic.start.main], (2.1) for
main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used. The valid C++ main signatures are:int main(void)and
int main(int argc, char **argv)which is equivalent to
int main(int argc, char *argv[])It is also worth noting that in C++,
int main() can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0; should be omitted or not is open to debate. The range of valid C program main signatures is much greater.Efficiency is not an issue with the
main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.You find the C++ specifications in [basic.start.main], (2.1) for
int main(), (2.2) for int main(int argc, char **argv) and (5) for the default return 0;.Code Snippets
int main(void)int main(int argc, char **argv)int main(int argc, char *argv[])Context
Stack Overflow Q#204476, score: 673
Revisions (0)
No revisions yet.