Which is a better choice to exit a Console, "FreeConsole (void)", "return 0", or "exit (EXIT_SUCCESS)"?

StackOverflow https://stackoverflow.com/questions/20100816

Question

I know about the difference between between return vs exit().
I want to know how they are different from FreeConsole().

  1. FreeConsole() is an API Function

  2. (scope: main function) return is a statement in C.

  3. exit (EXIT_SUCCESS) is a function call.

Which would you like to use in C to exit a program and why?

Was it helpful?

Solution 2

Which would you like to use in C to exit a program? Why and why not?

I wouldn't use FreeConsole() because I never program for Microsoft platforms; you shouldn't use it if you want your code to be portable. From the documentation you link to, it seems to do something completely different (detach from the console without ending the program), so you can't use it to end the program in any case.

Within main, I'd use return to ensure local variables are destroyed. exit() won't do that. (Although that's a habit from C++; in C, it makes little difference).

To end the program from other functions, return won't work, so I'd use exit(). But only if I'm convinced that it makes sense to end the program at that point.

In my opinion, return and exit() are the same. Is it correct?

From main(), almost. return will destroy local variables before ending the program; exit() won't.

(That only applies to C++; in C, where nothing has a destructor, they are effictively the same. Perhaps you should restrict your questions to one language at a time; I didn't initially notice that you'd tagged the question with two different languages.)

From other functions, they obviously aren't the same at all.

OTHER TIPS

In C, calling exit is equivalent to returning from main.

In C++, calling exit will bypass stack unwinding, so destructors will not be invoked properly (IOW, you almost always want to avoid it).

FreeConsole frees a console without exiting the program. The process can continue to execute detached after freeing the console. As such, it's not really even close to equivalent to either of the other two. Of course, FreeConsole is a Win32 API function, so using it also renders the code non-portable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top