[c++] Should I return EXIT_SUCCESS or 0 from main()?

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;}


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.

This question is related to c++ c return-value main

The answer is

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), 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_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- 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 implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 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 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

0 is, by definition, a magic number. EXIT_SUCCESS is almost universally equal to 0, happily enough. So why not just return/exit 0?

exit(EXIT_SUCCESS); is abundantly clear in meaning.

exit(0); on the other hand, is counterintuitive in some ways. Someone not familiar with shell behavior might assume that 0 == false == bad, just like every other usage of 0 in C. But no - in this one special case, 0 == success == good. For most experienced devs, not going to be a problem. But why trip up the new guy for absolutely no reason?

tl;dr - if there's a defined constant for your magic number, there's almost never a reason not to used the constant in the first place. It's more searchable, often clearer, etc. and it doesn't cost you anything.

This is a never ending story that reflect the limits (an myth) of "interoperability and portability over all".

What the program should return to indicate "success" should be defined by who is receiving the value (the Operating system, or the process that invoked the program) not by a language specification.

But programmers likes to write code in "portable way" and hence they invent their own model for the concept of "operating system" defining symbolic values to return.

Now, in a many-to-many scenario (where many languages serve to write programs to many system) the correspondence between the language convention for "success" and the operating system one (that no one can grant to be always the same) should be handled by the specific implementation of a library for a specific target platform.

But - unfortunatly - these concept where not that clear at the time the C language was deployed (mainly to write the UNIX kernel), and Gigagrams of books where written by saying "return 0 means success", since that was true on the OS at that time having a C compiler.

From then on, no clear standardization was ever made on how such a correspondence should be handled. C and C++ has their own definition of "return values" but no-one grant a proper OS translation (or better: no compiler documentation say anything about it). 0 means success if true for UNIX - LINUX and -for independent reasons- for Windows as well, and this cover 90% of the existing "consumer computers", that - in the most of the cases - disregard the return value (so we can discuss for decades, bu no-one will ever notice!)

Inside this scenario, before taking a decision, ask these questions: - Am I interested to communicate something to my caller about my existing? (If I just always return 0 ... there is no clue behind the all thing) - Is my caller having conventions about this communication ? (Note that a single value is not a convention: that doesn't allow any information representation)

If both of this answer are no, probably the good solution is don't write the main return statement at all. (And let the compiler to decide, in respect to the target is working to).

If no convention are in place 0=success meet the most of the situations (and using symbols may be problematic, if they introduce a convention).

If conventions are in place, ensure to use symbolic constants that are coherent with them (and ensure convention coherence, not value coherence, between platforms).

Once you start writing code that can return a myriad of exit statuses, you start #define'ing all of them. In this case EXIT_SUCCESS makes sense in context of not being a "magic number". This makes your code more readable because every other exit code will be EXIT_SOMETHING. If you simply write a program that will return when it's done, return 0 is valid, and probably even cleaner because it suggests that there's no sophisticated return code structure.

What you return from a program is just a convention.

No, I can't think of any circumstances where "EXIT_SUCCESS" wouldn't be "0".

Personally, I'd recommend "0".


If you use EXIT_SUCCESS, your code will be more portable.


Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.

Questions with c++ tag:

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++ How to enable C++17 compiling in Visual Studio? Remove from the beginning of std::vector Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? What is (x & 1) and (x >>= 1)? What are the new features in C++17? Visual Studio Code includePath Compiling an application for use in highly radioactive environments "No rule to make target 'install'"... But Makefile exists How to build and use Google TensorFlow C++ api Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Converting std::__cxx11::string to std::string lvalue required as left operand of assignment error when using C++ How to overcome "'aclocal-1.15' is missing on your system" warning? MSVCP140.dll missing How to get image width and height in OpenCV? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found Reading json files in C++ What exactly is std::atomic? Compile c++14-code with g++ Visual Studio 2015 doesn't have cl.exe Visual Studio 2013 error MS8020 Build tools v140 cannot be found CMake does not find Visual C++ compiler Casting int to bool in C/C++ C++ How do I convert a std::chrono::time_point to long and back How can I get the size of an std::vector as an int? Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); Fatal error: iostream: No such file or directory in compiling C program using GCC unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2 How to end C++ code How to change text color and console color in code::blocks? Error: stray '\240' in program invalid use of non-static member function Convert float to string with precision & number of decimal digits specified? enum to string in modern C++11 / C++14 / C++17 and future C++20 Passing capturing lambda as function pointer How do I add a library path in cmake? error: expected primary-expression before ')' token (C) undefined reference to 'std::cout' java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader fatal error: mpi.h: No such file or directory #include <mpi.h>

Questions with c tag:

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf? How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption How does one set up the Visual Studio Code compiler/debugger to GCC? How to add a char/int to an char array in C? Fork() function in C Warning comparison between pointer and integer Unsigned values in C How to run C program on Mac OS X using Terminal? How to printf a 64-bit integer as hex? Casting int to bool in C/C++ Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); "Multiple definition", "first defined here" errors error C4996: 'scanf': This function or variable may be unsafe in c programming Fatal error: iostream: No such file or directory in compiling C program using GCC What is the symbol for whitespace in C? How to change text color and console color in code::blocks? How to build x86 and/or x64 on Windows from command line with CMAKE? error: expected primary-expression before ')' token (C) C compile : collect2: error: ld returned 1 exit status How to use execvp() What does "collect2: error: ld returned 1 exit status" mean? socket connect() vs bind() fatal error: mpi.h: No such file or directory #include <mpi.h> How to scanf only integer? Abort trap 6 error in C Can someone explain how to append an element to an array in C programming? Returning string from C function Difference between using Makefile and CMake to compile the code How to convert const char* to char* in C? C convert floating point to int "break;" out of "if" statement? How to compile and run C in sublime text 3? How do I use setsockopt(SO_REUSEADDR)? Reading string by char till end of line C/C++ How to set all elements of an array to zero or any same value? The differences between initialize, define, declare a variable how to stop a loop arduino 'readline/readline.h' file not found size of uint8, uint16 and uint32? warning: control reaches end of non-void function [-Wreturn-type] Char Comparison in C

Questions with return-value tag:

Multiple values in single-value context MySQL stored procedure return value Best way to return a value from a python script How to return a value from try, catch, and finally? Return value in a Bash function How to return a string from a C++ function? Efficient way to return a std::vector in c++ Return value from a VBScript function store return value of a Python script in a bash script How can I return two values from a function in Python? Should I return EXIT_SUCCESS or 0 from main()? Returning value from called function in a shell script JOptionPane Yes or No window Jquery function return value Calling stored procedure with return value C# function to return array Return multiple values from a function, sub or type? Difference between return and exit in Bash functions MATLAB - multiple return values from a function? How to return a string value from a Bash function How to return 2 values from a Java method? How to return a result from a VBA function Return a "NULL" object if search result not found How do I return multiple values from a function in C? Return value from nested function in Javascript returning a Void object Android ACTION_IMAGE_CAPTURE Intent How to assign from a function which returns more than one value? Should functions return null or an empty object? How do I execute a command and get the output of the command within C++ using POSIX? How do I make the method return type generic? How do I return multiple values from a function? What should main() return in C and C++?

Questions with main tag:

String method cannot be found in a main class method How to access global variables Maven Error: Could not find or load main class Eclipse error "Could not find or load main class" Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) What does "Could not find or load main class" mean? C# importing class into another class doesn't work In Python, can I call the main() of an imported module? Can there exist two main methods in a Java program? Could not find or load main class with a Jar File Explanation of 'String args[]' and static in 'public static void main(String[] args)' Can't execute jar- file: "no main manifest attribute" int main() vs void main() in C Should I return EXIT_SUCCESS or 0 from main()? What is the Eclipse shortcut for "public static void main(String args[])"? C++ Fatal Error LNK1120: 1 unresolved externals "Error: Main method not found in class MyClass, please define the main method as..." calling another method from the main method in java What is the proper declaration of main in C++? Using Spring 3 autowire in a standalone Java application What is "String args[]"? parameter in main method Java What does if __name__ == "__main__": do? What should main() return in C and C++? Why is the Java main method static?