Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Oct 26, 2004

Returning from main()

Semantically, returning from main is as if the program called exit (found in <cstdlib> in C++ and <stdlib.h> in C) with the same value that was specified in the return statement. One way to think about this is that the startup code which calls main effectively looks like this:

// ...low-level startup code provided by vendor
exit(main(count, vector)); 
This is okay—even if you explicitly call exit from your program, which is another valid way to terminate your program (though in the case of main many prefer to return from it. Note that C, but not C++, allows main to be called recursively, in which case returning will just return the appropriate value to wherever it was called from.

Also, note that C++ destructors won't get run on ANY automatic objects if you call exit, nor obviously on some new objects. So there are exceptions to the semantic equivalence I've shown above.

The values which can be used for program termination are 0, EXIT_SUCCESS, or EXIT_FAILURE (these macros can also be found in stdlib.h in C and cstdlib in C++), representing a successful or unsuccessful program termination status respectively. The intention is for the operating system to do something with the value of the status along these same lines, representing success or not. If you specify some other value, the status is implementation-defined.

What if your program does not call exit, or your main does not return a value? Well, first of all, if the program really is expected to end, then it should. However, if you don't code anything (and the program is not in a loop), a return 0; is effectively executed once the flow of execution reaches the terminating brace of main. In other words, the following program:


int main() { } 
is effectively turned into this:

int main() { return 0; } 
Some C++ compilers or C compilers may not yet support this (and some folks consider it bad style not to code it yourself anyway). Note that an implication of this is that your compiler may issue a diagnostic that your main is not returning a value, since it is usually declared to return an int. So, in the following code, since exit is a library function, you may or may not have to add a bogus return statement just to satisfy it:

int main() { exit(0); } 
Mohan Bisht
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap