C语言中的布尔值



intcharfloat类型不同,ANSI C标准没有内置或主要的布尔类型。布尔值或bool数据通常指的是可以保存两个二进制值之一的数据:true或false(或yes/no,on/off等)。即使C语言中没有bool类型,您也可以借助enum类型实现布尔值的特性。

符合C99标准或更高版本的C编译器的新版本支持bool类型,该类型已在头文件stdbool.h中定义。

使用enum在C语言中实现布尔类型

enum类型将用户定义的标识符赋给整型常量。我们可以定义一个枚举类型,其中true和false作为标识符,其值为1和0。

示例

1或任何其他非0数字表示true,而0表示false。

Open Compiler
#include <stdio.h> int main (){ enum bool {false, true}; enum bool x = true; enum bool y = false; printf ("%d\n", x); printf ("%d\n", y); }

输出

运行代码并检查其输出 -

1
0

将typedef enum 定义为BOOL

为了使其更简洁,我们可以使用typedef关键字将enum bool称为BOOL。

示例1

请看下面的例子 -

Open Compiler
#include <stdio.h> int main(){ typedef enum {false, true} BOOL; BOOL x = true; BOOL y = false; printf ("%d\n", x); printf ("%d\n", y); }

在这里,您也将获得相同的输出 -

输出

1
0

示例2

我们甚至可以在决策或循环语句中使用枚举常量 -

Open Compiler
#include <stdio.h> int main(){ typedef enum {false, true} BOOL; int i = 0; while(true){ i++; printf("%d\n", i); if(i >= 5) break; } return 0; }

输出

运行此代码时,将产生以下输出 -

1
2
3
4
5

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用#define的布尔值

#define预处理器指令用于定义常量。我们可以用它来定义布尔常量,FALSE为0,TRUE为1。

示例

请看下面的例子 -

Open Compiler
#include <stdio.h> #define FALSE 0 #define TRUE 1 int main(){ printf("False: %d \n True: %d", FALSE, TRUE); return 0; }

输出

运行代码并检查其输出 -

False: 0 
 True: 1

stdbool.h中的布尔类型

C语言的C99标准引入了stdbool.h头文件。它包含bool类型的定义,实际上是_bool类型的typedef别名。它还定义了宏true(展开为1)和false(展开为0)。

示例1

我们可以按如下方式使用bool类型 -

Open Compiler
#include <stdio.h> #include <stdbool.h> int main(){ bool a = true; bool b = false; printf("True: %d\n", a); printf("False: %d", b); return 0; }

输出

执行此代码后,您将获得以下输出 -

True: 1
False: 0

示例2

我们也可以在逻辑表达式中使用bool类型变量,如下例所示 -

Open Compiler
#include <stdio.h> #include <stdbool.h> int main(){ bool x; x = 10 > 5; if(x) printf("x is True\n"); else printf("x is False\n"); bool y; int marks = 40; y = marks > 50; if(y) printf("Result: Pass\n"); else printf("Result: Fail\n"); }

输出

运行代码并检查其输出 -

x is True
Result: Fail

示例3

让我们用bool变量实现一个while循环 -

Open Compiler
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(void){ bool loop = true; int i = 0; while(loop){ i++; printf("i: %d \n", i); if (i >= 5) loop = false; } printf("Loop stopped!\n"); return EXIT_SUCCESS; }

输出

运行此代码时,将产生以下输出 -

i: 1
i: 2
i: 3
i: 4
i: 5
Loop stopped!
广告