What is the correct (most efficient) way to define the
main() function in C and C++ —
int main() or
void main() — and why?
int main() then
return 1 or
There are numerous duplicates of this question, including:
main()'s signature in C++
main()? — For C++, with a very good answer indeed.
main()functions in C
main()method in C
void main()in C
int main(int argc, char **argv)
int main(int argc, char *argv)
char *envpas a third argument to
int main()function return a value in all compilers?
main()function in C and C++ left to the user to define?
The return value for
main should indicate how the program exited. Normal exit is generally represented by a 0 return value from
main. Abnormal exit is usually signalled by a non-zero return, but there is no standard for how non-zero codes are interpreted. Also as noted by others,
void main() is explicitly prohibited by the C++ standard and shouldn't be used. The valid C++
main signatures are:
int main(int argc, char* argv)
which is equivalent to
int main(int argc, char** argv)
It's 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.
Also, 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, the case is different and re-entering
main() is allowed, but should be avoided.
The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways.
ISO/IEC 9899:1989 (C90):
main() should be declared as either:
int main(void) int main(int argc, char **argv)
Or equivalent. For example,
int main(int argc, char *argv) is equivalent to the second one. Further, the
int return type can be omitted as it is a default.
If an implementation permits it,
main() can be declared in other ways, but this makes the program implementation defined, and no longer strictly conforming.
The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour):
EXIT_SUCCESS for a successful termination, and
EXIT_FAILURE for an unsuccessful termination. Any other values are non-standard and implementation defined.
main() must have an explicit
return statement at the end to avoid undefined behaviour.
Finally, there is nothing wrong from a standards point of view with calling
main() from a program.
ISO/IEC 9899:1999 (C99):
For C99, everything is the same as above except:
intreturn type may not be omitted.
main(). If you do, and
main()finished, there is an implicit