Welcome! Log In Create A New Profile

Advanced

exit() vs. return

Posted by diego_pmc 
exit() vs. return
June 07, 2010 01:57AM
I've read that you should not return from main() and instead you should use exit(). Why is that?
Re: exit() vs. return
June 07, 2010 03:35PM
I don't know where you read that, but I think it's mostly better to use return, expecially from main.
+ You can control the execution flow cleanup before quit: free pointers and close files for example
+ Ansi C main signature is int main(int argc, char** argv), it MUST return the application status

Use exit and a atexit callback function when you can't do so (fatal error) or you are too lazy (return an error code from several functions calls to main)
Re: exit() vs. return
June 07, 2010 04:37PM
Regarding Wii homebrew, calling exit() is actually cleaner since it properly handles libogc exit (threads shutdown, memory freeing, return to HBC, etc). Remember there is no OS, if you just use "return", your application will hang and your only choice is to reboot the wii manually (well, I think so, never really tried).

Actually, there is absolutely no advantages in using "return", you can free your allocated memory pointers and close files before calling the exit() function like you do with return...



Edited 2 time(s). Last edit at 06/07/2010 04:40PM by ekeeke.
Re: exit() vs. return
June 07, 2010 05:45PM
I'm not 100% sure (couldn't find the devkitPro startup code) but main is usually called like this:
exit(main(argc, argv));
Re: exit() vs. return
June 08, 2010 01:36AM
Actually Daid is correct, the code looks like this:

void __crtmain() {
	__init();
	SYS_PreMain();
	exit ( main(__system_argv->argc,__system_argv->argv) );
}

So that means it doesn't really matter if you call exit() within your app, or just return from main. Typically I close my files, reset GX, and call exit(), but neither is more correct than the other. Also, FYI it's pointless to free memory before exiting - there's no OS so the state of your app and all its memory is lost when you exit.
Re: exit() vs. return
June 08, 2010 05:06PM
Quote

So that means it doesn't really matter if you call exit() within your app, or just return from main.
If you declare a C++ object locally (e.g. on the stack), when you call exit(), that object never goes out of scope. This means that object is never destructed. I think that's a big deal if you're doing something important in your destructors. I use exit() only when something bad happens, and I can't easily get back to the closing brace inside my main. Otherwise, I return from main.
Sorry, only registered users may post in this forum.

Click here to login