C没有任何内置布尔类型。在C语言中使用它们的最佳方式是什么?
当前回答
您可以简单地使用#define指令,如下所示:
#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;
使用方法如下:
bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);
等等
其他回答
可以使用_Bool,但返回值必须是整数(1表示真,0表示假)。但是,建议在C++中包含和使用bool,如中所述这个来自daniweb论坛的回答,以及来自另一个stackoverflow问题的回答:
_布尔:C99的布尔类型。只有在维护已经为Bool、true或false定义宏的遗留代码时,才建议直接使用_Bool。否则,这些宏将在标题中标准化。包含该标头,您可以像在C++中一样使用bool。
typedef enum {
false = 0,
true
} t_bool;
如果您使用的是C99编译器,它内置了对布尔类型的支持:
#include <stdbool.h>
int main()
{
bool b = false;
b = true;
}
http://en.wikipedia.org/wiki/Boolean_data_type
您可以简单地使用#define指令,如下所示:
#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;
使用方法如下:
bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);
等等
在布尔运算中,任何非零的值都被计算为真,因此您可以
#define TRUE 1
#define FALSE 0
并使用常数。