Search code examples
cbooleanreturn-valuetypeerrorreturn-code

Is it a bad idea to mix bool and ret codes


I have some programs which make heavy use of libraries with enumerations of error codes.

The kind where 0(first value of enum) is success and 1 is failure. In some cases I have my own helper functions that return bool indicating error, in other cases I bubble up the error enumeration. Unfortunately sometimes I mistake one for the other and things fail.

What would you recommend? Am I missing some warnings on gcc which would warn in these cases?

P.S. it feels weird to return an error code which is totally unrelated to my code, although I guess I could return -1 or some other invalid value.


Solution

  • Is it a bad idea? No, you should do what makes sense rather than following some abstract rule (the likes of which almost never cater for all situations you're going to encounter anyway).

    One way I avoid troubles is to ensure that all boolean-returning function read like proper English, examples being isEmpty(), userFlaggedExit() or hasContent(). This is distinct from my normal verb-noun constructs like updateTables(), deleteAccount() or crashProgram().

    For a function which returns a boolean indicating success or failure of a function which would normally follow that verb-noun construct, I tend to use something like deleteAccountWorked() or successfulTableUpdate().

    In all those boolean-returning cases, I can construct an easily readable if statement:

    if (isEmpty (list)) ...
    if (deleteAccountWorked (user)) ...
    

    And so on.

    For non-boolean-returning functions, I still follow the convention that 0 is okay and all other values are errors of some sort. The use of intelligent function names usually means it's obvious as to which is which.


    But keep in mind, that's my solution. It may or may not work for other people.