与 C++ 中使用 bool 不需要头文件不同,在 C 中使用 bool 必须包含头文件“stdbool.h”。如果我们将下面的程序保存为 .c,它不会编译,但如果我们保存它作为.cpp,它会正常工作。
如果我们在上述程序中包含头文件“stdbool.h”,它将作为 C 程序正常工作。
还有另一种方法可以在 C 语言中使用 enum 函数。您可以使用枚举创建一个布尔值。一个 enum 将被创建为 bool,然后将 enum 的元素分别设置为 True 和 False。false 将在第一个位置,因此它将保持 0,而 true 将在第二个位置,因此它将获得值 1。
下面是上述思想的实现:
输出
int main()
{
bool arr[2] = {true, false};
return 0;
}
#include <stdbool.h>
int main()
{
bool arr[2] = { true, false };
return 0;
}
// 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