After programming in C for several years, I realized that I have been ignoring the C convention of returning zero from a function to indicate success. The convention seems semantically wrong to me, as zero is of course false. The problem is I like to name functions like is_valid_foobar()
, and in order to accomodate the convention of 'false means success', I would have to be more vague...
that is instead of:
if ( ! is_valid_foobar() ) {
return (error);
}
Other programmers write:
if ( validate_foobar() ) {
return (error);
}
And my implementation looks like:
int is_valid_foobar (int foobar ) {
if ( foobar < MAX_ALLOWED ) {
return TRUE;
}
return FALSE;
}
I haven't actually caught any flak for this in code reviews. So I'm thinking it's not such a terrible habit, but it is 'unconventional'. I'm curious what people think.
I'm very careful about the choices I make for function and variable names, and a typical review comment is "the code is really clear", and further it doesn't bother me at all to have to type an extra !
at the front of the function call. But what sayest thou, oh mighty ones of S.O?
true and false are C++. C doesn't have them. … unless you #include <stdbool.
Bool function returns always true in C.
In an if statement, or any case where a boolean value (True or false) is being tested, in C, at least, 0 represents false, and any nonzero integer represents true.
I'd say both are correct, for different purposes:
If you're performing a simple go/no-go validation, e.g. is_numeric(), then true and false work nicely.
For something more elaborate, the 0==success paradigm is helpful in that it allows more than one error condition to be returned.
In this case, the caller can simply test against 0, or examine the non-0 returns for a more-specific explanation of the failure. e.g. a file open call can fail due to non-existence, insufficient permissions, etc.
The convention isn't exactly what you seem to think. Processes should exit with a 0 status to indicate success, and functions that return error codes will often use 0 to indicate "no error". But as a boolean, 0 should mean false and nonzero should mean true. To use 0 for boolean true will get you on The Daily WTF someday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With