bool在C中的使用

先决条件: C++中的BOOL数据类型 这个 C语言的C99标准 支持布尔变量。与C++不同,在没有使用头文件的情况下,使用BoL,头文件“STDBOOL .H”必须包含在C中使用BoOL,如果我们将下面的程序保存为。c、 它不会编译,但如果我们将其另存为。cpp,它会很好用的。

null

C

int main()
{
bool arr[2] = { true , false };
return 0;
}


如果我们在上面的程序中包含头文件“stdbool.h”,它将作为C程序正常工作。

C

#include <stdbool.h>
int main()
{
bool arr[2] = { true , false };
return 0;
}


在C语言中使用enum函数还有另外一种方法。可以使用enum创建bool。一个enum将被创建为bool,然后将enum的元素分别设置为True和False。false将位于第一个位置,因此它将保持0,true将位于第二个位置,因此它将得到值1。

以下是上述理念的实施情况:

C

// 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 false" );
}
else {
printf ( "bool1 is true" );
}
bool2 = 2;
if (bool2 == F) {
printf ( "bool2 is false" );
}
else {
printf ( "bool2 is true" );
}
}


输出

bool1 is false
bool2 is true

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享