1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > c语言中有布尔型变量 C语言的布尔型(bool)

c语言中有布尔型变量 C语言的布尔型(bool)

时间:2022-10-18 06:15:20

相关推荐

c语言中有布尔型变量 C语言的布尔型(bool)

Technorati 标签: C,布尔,boolean,_Bool,stdbool.h

也许很多人都和我一样,不知道现在的C语言已经有了布尔型:从C99标准开始,类型名字为“_Bool”。

在此之前的C语言中,使用整型int来表示真假。在输入时:使用非零值表示真;零值表示假。在输出时:真的结果是1,假的结果是0;(这里我所说的“输入”,意思是:当在一个需要布尔值的地方,也就是其它类型转化为布尔类型时,比如

if 条件判断中的的条件;“输出”的意思是:程序的逻辑表达式返回的结果,也就是布尔类型转化为其他类型时,比如

a==b的返回结果,只有0和1两种可能)。

所以,现在只要你的编译器支持C99(我使用的是Dev

C++4.9.9.2),你就可以直接使用布尔型了。另外,C99为了让C和C++兼容,增加了一个头文件stdbool.h。里面定义了bool、true、false,让我们可以像C++一样的定义布尔类型。

1. 我们自己定义的“仿布尔型”

在C99标准被支持之前,我们常常自己模仿定义布尔型,方式有很多种,常见的有下面两种:

#define TRUE 1

#define FALSE

0

enum

bool{false, true};

#define TRUE 1

#define FALSE 0

enum bool{false, true};

2. 使用_Bool

现在,我们可以简单的使用 _Bool 来定义布尔型变量。_Bool类型长度为1,只能取值范围为0或1。将任意非零值赋值给_Bool类型,都会先转换为1,表示真。将零值赋值给_Bool类型,结果为0,表示假。

下面是一个例子程序。

#include

#include

int

main(){

_Bool a = 1;

_Bool b = 2;

_Bool c = 0;

_Bool d = -1;

printf("a==%d, /n",

a);

printf("b==%d,

/n", b);

printf("c==%d, /n",

c);

printf("d==%d,

/n", d);

printf("sizeof(_Bool) ==

%d /n", sizeof(_Bool));

system("pause");

return

EXIT_SUCCESS;

}

#include

#include

int main(){

_Bool a = 1;

_Bool b = 2;

_Bool c = 0;

_Bool d = -1;

printf("a==%d, /n", a);

printf("b==%d, /n", b);

printf("c==%d, /n", c);

printf("d==%d, /n", d);

printf("sizeof(_Bool) == %d /n", sizeof(_Bool));

system("pause");

return EXIT_SUCCESS;

}

运行结果如下:(只有0和1两种取值)

a==1,

b==1,

c==0,

d==1,

sizeof(_Bool) == 1

a==1,

b==1,

c==0,

d==1,

sizeof(_Bool) == 1

3. 使用stdbool.h

在C++中,通过bool来定义布尔变量,通过true和false对布尔变量进行赋值。C99为了让我们能够写出与C++兼容的代码,添加了一个头文件<stdbool.h>。在gcc中,这个头文件的源码如下:(注,为了清楚,不重要的注释部分已经省略)

#ifndef

_STDBOOL_H

#define _STDBOOL_H

#ifndef __cplusplus

#define bool _Bool

#define true

1

#define false 0

#else

#define _Bool

bool

#define bool bool

#define false

false

#define true true

#endif

#define

__bool_true_false_are_defined 1

#endif

#ifndef _STDBOOL_H

#define _STDBOOL_H

#ifndef __cplusplus

#define bool _Bool

#define true 1

#define false 0

#else

#define _Bool bool

#define bool bool

#define false false

#define true true

#endif

#define __bool_true_false_are_defined 1

#endif

可见,stdbool.h中定义了4个宏,bool、true、false、__bool_true_false_are_defined。

其中bool就是

_Bool类型,true和false的值为1和0,__bool_true_false_are_defined的值为1。

下面是一个例子程序:

#include

#include

#include

int

main(){

bool m =

true;

bool n

= false;

printf("m==%d, n==%d

/n", m, n);

printf("sizeof(_Bool) == %d

/n", sizeof(_Bool));

system("pause");

return

EXIT_SUCCESS;

}

#include

#include

#include

int main(){

bool m = true;

bool n = false;

printf("m==%d, n==%d /n", m, n);

printf("sizeof(_Bool) == %d /n", sizeof(_Bool));

system("pause");

return EXIT_SUCCESS;

}

执行结果为:

m==1, n==0

sizeof(_Bool) ==

1

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。