Time to standardize "true" and "false"

Tom Karzes karzes at mfci.UUCP
Tue Sep 26 05:33:27 AEST 1989


In article <895 at cirrusl.UUCP> dhesi%cirrusl at oliveb.ATC.olivetti.com (Rahul Dhesi) writes:
>(The referenced article had a follow-up header of "poster", which I
>think is a nasty thing to have done.)

I agree.

>I suggest that defensive programmers eschew these constants because the
>temptation to say
>
>     if (x == TRUE) ...
>
>may overcome you some day and you will suffer...

I agree that this sort of thing does happen, particularly in a language
like C which doesn't support a distinct boolean data type but does support
boolean operations defined on integers.  However, I feel that it is primarily
a matter of understanding and engineering discipline.  Proper use of a user
defined boolean data type will only attempt to represent canonical true and
false values in that data type.  It should be sufficient to define:

    typedef int     bool;
    #define FALSE   0
    #define TRUE    1

and to then only use bool to hold TRUE or FALSE (which includes values
generated by comparisons, !, &&, ||, etc.).  Under this usage, the following
constructs should never appear for bool's b, b1, and b2:

        bad form                preferred equivalent
    ----------------            --------------------
    b == FALSE                      ! b
    b != FALSE                      b
    b == TRUE                       b
    b != TRUE                       ! b
    b ? TRUE : FALSE                b
    b ? FALSE : TRUE                ! b
    b1 ? FALSE : b2                 (! b1) && b2
    b1 ? TRUE : b2                  b1 || b2
    b1 ? b2 : FALSE                 b1 && b2
    b1 ? b2 : TRUE                  (! b1) || b2

Expressions of type bool should not be used as integer expression unless
explicitly case to type int, to indicate that the F=0, T=1 behavior is
being assumed.  The need for this shouldn't arise very often (only in
tight little pieces of code where you want to do something like optionally
add 1 to a number, depending on a bool value, and you want it to be really
tight code so you simply add the cast bool, as opposed to "b ? 1 : 0").



More information about the Comp.lang.c mailing list