C语言中的 Bool 类型
最近在网上看到有的说法里是没有bool类型的,不过以前在书上好像看到过相关的介绍,就特意找出来了那本书《C Primer Plus》,确定了C语言里确实存在bool类型。C语言是在C99标准中添加的bool类型。
bool类型是以英国数学家 * George Boole * 命名的,是他开发了用线性代数表示并解决逻辑问题的系统。
在C语言中我们使用 _Bool 来定义bool类型的变量
下面定义了一个_Bool类型的变量,并把(1 == 3)的计算值赋值给test
c
1#include <stdio.h>
2
3int main ()
4{
5 _Bool test;
6 test = (1 == 3);
7 return 0;
8}下面能证明bool类型变量的特点 只有0和1两个值 只有0赋值给bool类型时,bool才为0
c
1#include <stdio.h>
2
3int main ()
4{
5 _Bool test;
6 int i;
7 for (i = -10; i < 10; i++)
8 {
9 test = i;
10 if (test)
11 printf ("true\n");
12 else
13 printf ("false\n");
14 }
15 return 0;
16}最后我们证明一下bool类型比int类型占的内存要少
c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main ()
5{
6 int myint;
7 _Bool mybool;
8 int memint;
9 int membool;
10
11 memint = sizeof(myint);
12 membool = sizeof(mybool);
13
14 printf ("int = %d\n", memint);
15 printf ("_Bool = %d\n", membool);
16 return 0;
17}如果这篇文章对你有帮助,可以请我喝杯咖啡 ☕
评论