What should main() return in C and C++?
In both C and C++, the main
function should (and by standard, must) return an int
value. This return value informs the environment (e.g., the operating system or calling process) about the program’s exit status:
return 0;
traditionally indicates successful execution.- Non-zero returns often indicate some kind of failure or error.
- In C++, if you omit an explicit
return
statement frommain
, many compilers automatically insertreturn 0;
for you (though it’s still best practice to write it explicitly).
Examples
int main() { // ... your code ... return 0; // signals success } // or, with arguments int main(int argc, char *argv[]) { // ... your code ... return someErrorCode ? 1 : 0; }
Recommended Resources
If you’re interested in more foundational knowledge or prepping for coding interviews, here are two recommended courses from DesignGurus.io:
- Grokking Data Structures & Algorithms for Coding Interviews – Strengthen your base in memory management, arrays, lists, and more.
- Grokking the Coding Interview: Patterns for Coding Questions – Learn key patterns repeatedly tested in interviews, helping you craft efficient solutions under time pressure.
By consistently returning an appropriate integer code from main
, you adhere to the language standards and provide valuable feedback to the calling environment regarding your program’s success or failure.
CONTRIBUTOR
TechGrind