I’m writing a web app that needs to use several ansi C functions to crunch data. Another language, probably Java, will call the main C function to trigger the process. I want to return a value from the main C function for the Java script to evaluate success or not. I expect C’s use of exit() was created for this reason.
As I go about programming C, there are several times I run into situations that I could evaluate to examine whether or not the program is running correctly. For example, if I have a variable that can only equal "equation 1", "equation 2" or "equation 3", and then I use an
if(var==equation1) {
/*statements*/
}
else if(var==equation2) {
/*statements*/
}
else if(var==equation3) {
/*statements*/
}
statements to check which of the three possibilities it is, I could add an else { } to the end, whose contents I expect will never execute in a normally running program, to catch unexpected problems. I want to place an exit(EXIT_FAILURE) in this last else { } statement. If I understand it correctly, this will cause the program to terminate, and return a non-zero value to the Java calling program for it to detect. Is that correct?
Can I sprinkle this exit(EXIT_FAILURE) throughout various functions, not just main(), for the same reason?
Some questions about the mechanics of setting this up — Is the main function simply setup as: int main(void); assuming no input arguments for simplicity? That is, the int is needed to return the integer value called by the macro EXIT_FAILURE… is that right?
If the main() function called another function, and that function contained an exit(EXIT_FAILURE) statement, does that other function need to specifically include a return in its prototype, e.g. int function_one(void); where the int is needed to return the EXIT_FAILURE status, or is the EXIT_FAILURE macro self-sufficient in this regard, so that if the function_one wants to return, say, a character, then its prototype can be char function_one(void); and no worry about returning anything for EXIT_FAILURE in its prototype?
The return type
intofmainis effectively the return value that the calling process sees. The general idea is that yourmaindoes this as any other function namelyreturn EXIT_FAILURE. Whenever possible you should use this direct approach.The function
exitcan be used to shortcut all this and to return to the caller from any other function thanmain. But the return value of a function that usesexithas nothing to do with the fact that it might to a preliminary exit throughexit. So you don’t have to change any prototype of your functions.Your other assumptions seem to be correct, and your use of
exitto terminate an invalid invocation looks valid to me.