It’s a simple question, but I keep seeing conflicting answers: should the main routine of a C++ program return 0 or EXIT_SUCCESS?
#include <cstdlib>
int main(){return EXIT_SUCCESS;}
or
int main(){return 0;}
Are they the exact same thing? Should EXIT_SUCCESS only be used with exit()?
I thought EXIT_SUCCESS would be a better option because other software may want to deem zero as failure, but I also heard that if you return 0, the compiler is capable of changing it to a different value anyway.
EXIT_FAILURE, either in a return statement inmainor as an argument toexit(), is the only portable way to indicate failure in a C or C++ program.exit(1)can actually signal successful termination on VMS, for example.If you’re going to be using
EXIT_FAILUREwhen your program fails, then you might as well useEXIT_SUCCESSwhen it succeeds, just for the sake of symmetry.On the other hand, if the program never signals failure, you can use either
0orEXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It’s barely possible thatEXIT_SUCCESScould have a value other than 0, but it’s equal to 0 on every implementation I’ve ever heard of.)Using
0has the minor advantage that you don’t need#include <stdlib.h>in C, or#include <cstdlib>in C++ (if you’re using areturnstatement rather than callingexit()) — but for a program of any significant size you’re going to be including stdlib directly or indirectly anyway.For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of
main()does an implicitreturn 0;anyway, so you might not need to use either0orEXIT_SUCCESSexplicitly. (But at least in C, I consider an explicitreturn 0;to be better style.)(Somebody asked about OpenVMS. I haven’t used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps
0to1, so thatreturn 0;indicates successful termination. Other values are passed unchanged, soreturn 1;also indicates successful termination.EXIT_FAILUREwould have a non-zero even value.)