Search code examples
c++cfunctionwinapimingw32

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


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?


Solution

  • 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.