Return value of a boolean expression in C

后端 未结 2 1997
Happy的楠姐
Happy的楠姐 2021-01-15 12:24

For reasons that are not worth mentioning, I want to know if there\'s a standard defined value for boolean expressions. E.g.

int foo () {
    return (bar >         


        
2条回答
  •  我在风中等你
    2021-01-15 12:40

    An operator such as ==, !=, &&, and || that results in a boolean value will evaluate to 1 of the expression is true and 0 if the expression is false. The type of this expressing is int.

    So if the TRUE macro is not defined as 1, a comparison such as the above will fail.

    When an expression is evaluated in a boolean context, 0 evaluates to false and non-zero evaluates to true. So to be safe, TRUE should be defined as:

    #define TRUE (!0)
    

    As was mentioned in the comments, if your compiler is C99 compliant, you can #include and use true and false.

    According to C99:

    6.5.3.3 (Unary arithmetic operators)

    The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

    6.5.8 (Relational operators)

    Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.

    6.5.9 (Equality operators)

    The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int.

    6.5.13 (Logical AND operator)

    The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

    6.5.14 (Logical OR operator)

    The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

提交回复
热议问题