Is comparing a BOOL against YES dangerous?

后端 未结 4 2105
轻奢々
轻奢々 2020-12-15 12:29

I found a comment today in a source file:

//  - no longer compare BOOL against YES (dangerous!)

Is comparing BOOL against

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 13:15

    You should never compare booleans against anything in any of the C based languages. The right way to do it is to use either:

    if (b)
    

    or:

    if (!b)
    

    This makes your code much more readable (especially if you're using intelligently named variables and functions like isPrime(n) or childThreadHasFinished) and safe. The reason something like:

    if (b == TRUE)
    

    is not so safe is that there are actually a large number of values of b which will evaluate to true, and TRUE is only one of them.

    Consider the following:

    #define FALSE 0
    #define TRUE  1
    
    int flag = 7;
    if (flag)         printf ("number 1\n");
    if (flag == TRUE) printf ("number 2\n");
    

    You should get both those lines printed out if it were working as expected but you only get the first. That's because 7 is actually true if treated correctly (0 is false, everything else is true) but the explicit test for equality evaluates to false.

    Update:

    In response to your comment that you thought there'd be more to it than coder stupidity: yes, there is (but I still wouldn't discount coder stupidity as a good enough reason - defensive programming is always a good idea).

    I also mentioned readability, which is rather high on my list of desirable features in code.

    A condition should either be a comparison between objects or a flag (including boolean return values):

    if (a == b) ...
    if (c > d) ...
    if (strcmp (e, "Urk") == 0) ...
    if (isFinished) ...
    if (userPressedEsc (ch)) ...
    

    If you use (what I consider) an abomination like:

    if (isFinished == TRUE) ...
    

    where do you stop:

    if (isFinished == TRUE) ...
    if ((isFinished == TRUE) == TRUE) ...
    if (((isFinished == TRUE) == TRUE) == TRUE) ...
    

    and so on.

    The right way to do it for readability is to just use appropriately named flag variables.

提交回复
热议问题