Search code examples
creturn-value

define bool return value in c


I have one question for return value in C, I want to use "true" "false" to mark the condition for the function. But in C, return 0(false) means normal while return 1(true) means issues. So I define as true, 1 as false? Or I'd better just don't use the bool type to avoid this conflict?


Solution

  • This cannot be answered generally except that you should never "define" 0 as true and 1 as false since that is directly opposite of the Standard definition.

    This is a case where you need to make a convention (decision) in your program and stick to it. There are at least two common solutions:

    1. Return a bool where true means "success" and false means "failure".
    2. Return an error code where 0 means no error and a non-zero value indicates the precise error which occurred. In this case, error codes may be specific for the function or common across the program. This is, by the way, the convention used in the Standard for the main() function, but there is not a strong practice dictating that this must be the case for other functions in the program as well.

    There are other possibilities and the most important is to be consistent within the same category of functions (again, it is up to you to define what this means in your specific context).

    If you choose to use a boolean return type, you should use the standard bool type:

    #include <stdbool.h>
    
    bool func()
    {
       ...
       if(error) return false;  // Failure
       return true;  // Success
    }