Pergunta

There are many ways how to exit program in C. Some of them are returning zero or error code, using exit function with EXIT_SUCCESS, EXIT_FAILURE, exit(0), exit(1) or some other error code, abort and probably few more I can't think of now.

My question is which option is the best and why. I'm asking here because every time I asked more experienced programmers this question, it ended up as a holy war.

Foi útil?

Solução

I think the best thing is return EXIT_SUCCESS or return a non-zero number for which you have documented an error code, or EXIT_FAILURE if you can't define error codes for all the conditions that could cause you to fail. This would let a program using your program (in a pipe or batch function) actually use your error code to determine what to do next if applicable.

Personally I am not married to macros that always, on every single implementation on earth equal 0 but hey that sort of comment can get you downvoted.

Outras dicas

There is no one "best". If you want to maximize portability, you can only use three values: EXIT_SUCCESS, EXIT_FALURE, and 0 (and 0 and EXIT_SUCCESS mean the same thing). If you don't mind losing some portability, it's often useful to return various other values to indicate why something failed, or (in some cases) return a non-zero value even in case of success to indicate things like how many of X it found, or carry the result of a calculation, etc.

As such, you have a choice between portability (but mostly to systems you probably don't care about, chiefly VMS) and functionality on a slightly reduced set of systems. You have to decide which is more important to you.

Edit: No, EXIT_SUCCESS does not always equal zero -- but (at least as far as the standard cares) the two mean the same thing. There was at least one compiler on VMS, however, that defined EXIT_SUCCESS to a non-zero value (VMS normally interpreted even numbers as failure and odd numbers as success, so EXIT_SUCCESS was defined to the proper odd number, and 0 was treated specially, so the system got an odd number when/if you returned it).

Licenciado em: CC-BY-SA com atribuição
scroll top