如何在C中使用布尔数据types?

我只是写在C代码,事实certificate,它没有一个布尔/布尔数据types。 有没有我可以包含的C库,使我能够返回一个布尔值/布尔型数据types?

如果你有一个支持C99的编译器,你可以

#include <stdbool.h> 

否则,如果你愿意,你可以定义你自己的。 根据你想要如何使用它(以及是否希望能够将你的代码编译为C ++),你的实现可以像下面这样简单:

 #define bool int #define true 1 #define false 0 

在我看来,尽pipe如此,你也可以使用int并用零来表示假和非零来表示真。 这就是通常在C中完成的

C99实际上有一个布尔数据types,但是如果你必须使用旧版本,只需定义一个types:

 typedef enum {false=0, true=1} bool; 

C99有一个booltypes。 要使用它,

 #include <stdbool.h> 

作为James McNellis的替代答案,我总是尝试使用枚举来代替macros的布尔types: typedef enum bool {false=0; true=1;} bool; typedef enum bool {false=0; true=1;} bool; 。 这是更安全的B / C它让编译器进行types检查,并消除macros观扩展比赛

 struct Bool { int true; int false; } int main() { /* bool is a variable of data type – bool*/ struct Bool bool; /*below I'm accessing struct members through variable –bool*/ bool = {1,0}; print("Student Name is: %s", bool.true); return 0; }