C Standard Library 简明教程
C library - <stdbool.h>
C 库 <stdbool.h> 头文件支持 bool 数据类型。bool 可以将值存储为 true(0) 或 false(1),这是各种编程语言的常见需求。
The C library <stdbool.h> header supports the bool data types. The bool can store the value as true(0) or false(1) which is common requirement in various programming languages.
有三种方法来执行此头文件实现 −
There are three ways to perform the implementation of this header −
-
The stdbool.h − This is C header which support the boolean variable.
-
The Enumeration (enum) type − This is special type of data which is defined by the user. This includes either integral constant or integer.
-
Declare the boolean values − The value can be defined as true or false.
Example 1
以下是简单的 C 库头文件 <stdbool>,用于查看布尔值的整数形式转换。
Following is the simple C library header <stdbool> to see the conversion of boolean value in integer form.
#include <stdbool.h>
#include <stdio.h>
int main()
{
// Declaration of boolean data types
bool x = true;
bool y = false;
printf("True : %d\n", x);
printf("False : %d", y);
return 0;
}
Example 2
在程序下方创建一个枚举 (enum) 类型以显式表示布尔值。
Below the program create an enumeration(enum) type to represent boolean values explicitly.
#include <stdio.h>
enum Bool { FALSE, TRUE };
int main() {
enum Bool isTrue = TRUE;
enum Bool isFalse = FALSE;
// Rest of your code...
printf("isTrue: %d\n", isTrue);
printf("isFalse: %d\n", isFalse);
// Rest of your program logic...
return 0;
}
Example 3
在此,我们使用整数常量直接声明布尔值,它为 false 显示 0,为 true 显示 1。
Here, we directly declare the boolean value using integer constants which shows the 0 for false and 1 for true.
#include <stdio.h>
int main() {
int isTrue = 1; // true
int isFalse = 0; // false
printf("isTrue: %d\n", isTrue);
printf("isFalse: %d\n", isFalse);
return 0;
}