Reputation: 7320
Quick question.. is there a "proper" way to terminate from a C/C++ program on invalid input? Thus far, my career in C/C++ has involved doing something like this:
// C
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Error: Usage: %s [some param] [some param]\n", argv[0]);
return 1;
}
/* rest of program */
return 0;
}
In C++, it could be cerr
instead of fprintf(srderr...)
and iostream
instead or stdio.h
.
Is this an OK/acceptable way, or is there a standard I'm not aware of?
Thanks!
Upvotes: 3
Views: 2721
Reputation: 6054
Alternately, you can call exit()
function, instead of return
. That is within main, retrun exp
is equivalent to exit(exp)
. The argument of exit is available to whatever process called this, so the success or failure of the program can be tested by another program that uses this as a sub-process. Conventionally, a return value 0 signals that all is well; non-zero values usually signal abnormal situations.
exit
has the advantage that it can be called from other functions.
Upvotes: 1
Reputation: 143032
The basic convention is to return a non-zero value to indicate some error condition on exit. A return value of zero is used to indicate normal program termination.
There's nothing to prevent you from coming up with list of non-zero values and associating them with specific error conditions so that one could identify the specific error based on an exit value.
For instance if a shell program was running your program it could then take appropriate action by examining the exit value. Error messages to stderr are useful for us, but exit values can be used programatically and provide additional flexibility.
Usually values 0 - 127 are resevered for your use, the rest for the system according to Job crashes and exit codes
Upvotes: 11
Reputation: 9278
In the world of DOS .bat files it's the convention that programs that execute successfully return 0, this is then checked by the %ERRORLEVEL%
value in the batch file. Non-zero values indicate something went wrong, the exact value returned is really up to the programmer and should be documented somewhere. More here
Unix is very similar but seems to have a bit more specfication according to this
Upvotes: 1