Using true and false in C

后端 未结 15 1809
情书的邮戳
情书的邮戳 2020-12-01 01:52

As far as I can see there are 3 ways to use booleans in c

  1. with the bool type, from then using true and false
  2. defining using preprocessor #defin
相关标签:
15条回答
  • 2020-12-01 02:38

    I prefer to use

    #define FALSE (0!=0) 
    #define TRUE  (0==0)
    

    or directly in the code

    if (flag == (0==0)) { ... }
    

    The compiler will take care of that. I use a lot of languages and having to remember that FALSE is 0 bothers me a lot; but if I have to, I usually think about that string loop

    do { ... } while (*ptr);
    

    and that leads me to see that FALSE is 0

    0 讨论(0)
  • 2020-12-01 02:39

    With the stdbool.h defined bool type, problems arise when you need to move code from a newer compiler that supports the bool type to an older compiler. This could happen in an embedded programming environment when you move to a new architecture with a C compiler based on an older version of the spec.

    In summation, I would stick with the macros when portability matters. Otherwise, do what others recommend and use the bulit in type.

    0 讨论(0)
  • 2020-12-01 02:40

    Whichever of the three you go with, compare your variables against FALSE, or false.

    Historically it is a bad idea to compare anything to true (1) in c or c++. Only false is guaranteed to be zero (0). True is any other value.   Many compiler vendors have these definitions somewhere in their headers.  

    #define TRUE 1
    #define FALSE 0
    

    This has led too many people down the garden path.   Many library functions besides chartype return nonzero values not equal to 1 on success. There is a great deal of legacy code out there with the same behavior.

    0 讨论(0)
提交回复
热议问题