I recently saw something curious. In the HHVM source code, the very first 3 lines of the main()
function read as follows:
if (!argc) {
return 0;
}
It's a bit silly, but still, I just can't help wondering... why return 0!? It's not that I think there's some correct way to handle this, but returning 0, usually associated with success, seems particularly inappropriate.
Besides not crashing, is there ever a case where there's an appropriate response to argc
being 0? (Or even less than 0?) Does it ever matter?
The only way I know of to end up in a case with argc
of 0 is with exec()
and friends. If for some reason that does happen, it's almost certainly a bug in the caller and the callee can't do much about it.
(tagged as C and C++ because I expect that the answer is the same for the two languages)
Edit: To try and make the question less vague and philosophical, I'll offer an alternative.
if (!argc) {
puts("Error: argc == 0");
return 1;
}
The key points are that there's an indication of the error and a non-zero value is returned. It's extremely unlikely this would be needed, but if it was you might as well try to indicate the error. On the other hand, if the detected error is as serious as argc
equal to 0, maybe there's a reason it would be bad to try and access stdout or the C standard library.
I think it's just a case of Defensive programming due to the following snippet in the HHVM's sorce code (file hphp/hhvm/main.cpp):
int main(int argc, char** argv) {
if (!argc) {
return 0;
}
HPHP::checkBuild();
int len = strlen(argv[0]);
In the line:
int len = strlen(argv[0]);
if argc == 0
-> argv[0] == NULL
and strlen(argv[0])
will cause a segmentation fault.
I'm not familiar with HHVM but they can just suppose some program can call the program without arguments (not even the program name).