Correct use of EXIT_FAILURE in C program?

The return type int of main is effectively the return value that the calling process sees. The general idea is that your main does this as any other function namely return EXIT_FAILURE. Whenever possible you should use this direct approach.

The function exit can be used to shortcut all this and to return to the caller from any other function than main. But the return value of a function that uses exit has nothing to do with the fact that it might to a preliminary exit through exit. So you don't have to change any prototype of your functions.

Your other assumptions seem to be correct, and your use of exit to terminate an invalid invocation looks valid to me.


Yes, you can call exit(EXIT_FAILURE) anywhere in your program.

Notice that exit is related to atexit. See also _Exit (which is rarely useful) and abort


Yes, you can call exit from anywhere to terminate the program. Feel free to use it anywhere you think that your program should not continue.

Also instead of using generic EXIT_FAILURE, you might want to devise your own error codes so that you can give a little more info to the caller than just "Something went wrong". and use that with exit (remember you can call it with any 8-bit value, not just EXIT_FAILURE or EXIT_SUCCESS). For instance, 0 might be success, 1 might be input read failure, 2 might be input formatting error, and so on.

Tags:

C