Using true and false in C

2019-01-10 16:39发布

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 #define FALSE 0 ... #define TRUE !(FALSE)
  3. Just to use constants directly, i.e. 1 and 0

are there other methods I missed? What are the pros and cons of the different methods?

I suppose the fastest would be number 3, 2 is more easily readable still (although bitwise negation will slightly add to overhead), 1 is most readable not compatible with all compilers.

14条回答
冷血范
2楼-- · 2019-01-10 16:55

You can test if bool is defined in c99 stdbool.h with

#ifndef __bool_true_false_are_defined || __bool_true_false_are_defined == 0
//typedef or define here
#endif
查看更多
家丑人穷心不美
3楼-- · 2019-01-10 16:57

I usually do a:

typedef enum {FALSE = 0, TRUE} boolean;
查看更多
走好不送
4楼-- · 2019-01-10 16:57

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.

查看更多
家丑人穷心不美
5楼-- · 2019-01-10 16:59

I would go for 1. I haven't met incompatibility with it and is more natural. But, I think that it is a part of C++ not C standard. I think that with dirty hacking with defines or your third option - won't gain any performance, but only pain maintaining the code.

查看更多
▲ chillily
6楼-- · 2019-01-10 17:00

Any int other than zero is true; false is zero. That way code like this continues to work as expected:

int done = 0;   // `int` could be `bool` just as well

while (!done)
{
     // ...
     done = OS_SUCCESS_CODE == some_system_call ();
}

IMO, bool is an overrated type, perhaps a carry over from other languages. int works just fine as a boolean type.

查看更多
对你真心纯属浪费
7楼-- · 2019-01-10 17:01

I prefer (1) when i define a variable but in expressions i never compare against true and false just take the implicit C definition of if(flag) or if(!flag) or if(ptr). Thats the C way to do things.

查看更多
登录 后发表回答