浅谈C语言编程中的布尔bool数据类型
我们知道在C++里有专门的bool类型,用来表示真或假。但是在C语言里没有这样的类型(至少我是一直这么认为的),表达式的值0为假,非0为真。所以条件判断语句( if(…)、while(…) )非常灵活,甚至一个指针类型都可以是条件表达式。 typedef int BOOL; #define TRUE 1 #define FALSE 0 这是最常见的写法,能被任何C语言编译器认可。 /* * ISO C Standard: 7.16 Boolean type and values */ #ifndef _STDBOOL_H #define _STDBOOL_H #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #else /* __cplusplus */ /* Supporting in C++ is a GCC extension. */ #define _Bool bool #define bool bool #define false false #define true true #endif /* __cplusplus */ /* Signal that all the definitions are present. */ #define __bool_true_false_are_defined 1 #endif /* stdbool.h */ 这个头文件很短,而且也很明了,不过我对_Bool这个类型产生的兴趣。又一翻百度,发现这是C99标准引入的新的关键字。对,是关键字,而不是宏定义,也不是typedef。通过sizeof(_Bool);得知这个类型占1个字节,而且无论给这个类型的变量赋任何非0整数值,其值都是1,这也说明了他不是其他整数类型的别名。 typedef enum {false = 0,true = 1} bool; 那么我们就来看一下C语言中的相关定义: #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif 也就是说FALSE/TRUE是int类型,而false/true是bool类型;所以两者不一样的,只不过 #ifndef NULL #ifdef __cplusplus//这个是指示是用C++来编译程序 #define NULL 0 #else #define NULL ((void *)0) #endif #endif 所以说:它们没有区别,只不过在C里面会做一个强制类型转换。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |