Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return TRUE / FALSE values from a C function?

Tags:

c

return-value

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?

like image 900
Leonard Avatar asked Feb 17 '09 22:02

Leonard


People also ask

Can you return true or false in C?

true and false are C++. C doesn't have them. … unless you #include <stdbool.

Can a function return a boolean value in C?

Bool function returns always true in C.

What is the return value of true ()?

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.


2 Answers

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.

like image 69
Paul Roub Avatar answered Nov 02 '22 22:11

Paul Roub


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.

like image 20
Chuck Avatar answered Nov 02 '22 22:11

Chuck