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!
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