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?
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.