吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 在 C 中使用 bool

在 C 中使用 bool

来源:网络 | 更新时间:2022-01-08 12:25:10
先决条件:C++ 中的Bool 数据类型 C 语言的C99 标准支持 bool 变量。与 C++ 中使用 bool 不需要头文件不同,在 C 中使用 bool 必须包含头文件“stdbool.h”。如果我们将下面的程序保存为 .c,它将无法编译,但如果我们保存它作为.cpp,它会正常工作。  
int main()
{
bool arr[2] = {true, false};
return 0;
}
如果我们在上述程序中包含头文件“stdbool.h”,它将作为 C 程序正常工作。 
#include <stdbool.h>
int main()
{
bool arr[2] = { true, false };
return 0;
}
还有另一种方法可以在 C 语言中使用 enum 函数。您可以使用枚举创建一个布尔值。一个 enum 将被创建为 bool,然后将 enum 的元素分别设置为 True 和 False。false 将在第一个位置,因此它将保持 0,而 true 将在第二个位置,因此它将获得值 1。 下面是上述想法的实现:
// C implementation of the above idea
#include <stdio.h>

// Declaration of enum
typedef enum { F, T } boolean;

int main()
{
boolean bool1, bool2;
bool1 = F;

if (bool1 == F) {
printf("bool1 is falsen");
}
else {
printf("bool1 is truen");
}
bool2 = 2;
if (bool2 == F) {
printf("bool2 is falsen");
}
else {
printf("bool2 is truen");
}
}
输出
bool1 is false
bool2 is true
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com