cboolean

Which one is safer to use? " ==TRUE" or " != FALSE"


Is it better to compare a boolean type variable with:

  1. == FALSE and != FALSE; or
  2. == TRUE and != TRUE?

Solution

  • Is it better to compare a boolean type variable with " == FALSE" and " != FALSE" or with " ==FALSE" and " ==TRUE" ?

    1. Neither.

    With the C boolean type _Bool, (with C23: bool) do not use == or != to assess truth-ness against a constant.
    @Steve Summit @Antti Haapala @John Bode

    _Bool x;
    if (x)   // to assess truth-ness
    if (!x)   // to assess false-ness
    
    1. If a strong desire remains to use ==, !=, like many style issues, best to follow your group's coding guidelines.

    2. Lacking group's coding guidelines - make them.


    Pre-C23: Use <stdbool.h> as able to access bool, true, false rather than code TRUE, FALSE.
    @Eugene Sh.


    Which one is safer to use? “ ==TRUE” or “ != FALSE”

    Note that comparing a == TRUE can fail unexpectedly as the operands are compared as integers, FP or pointers, not as boolean. This may fail to compare truth-ness should a be a non-boolean with a "truth" value other than 1 even if TRUE is a boolean 1.

    double a = 0.999999;
    // Both are false
    if (a == TRUE) { ... }   // The arithmetic value of `a` is used, not its "truth"
    if (a == FALSE) { ... }
    // better as 
    if (a) { ... }   // As if `a != 0`
    else { ... }
    

    Consider cases where the "truth" is returned as non-zero, perhaps not 1.

    if(islower('a') == TRUTH) ...  // The if() block might or might not execute
    if(islower('a'))  ...          // The if() block will execute
    

    a != 0 or a != false tends to be safer.


    Style: I find == code easier to follow than != as negations add mental complexity for people. Example