结论
bool 布尔类型使用的,几个规则:
(1)stdbool宏定义了 true = 1,false = 0
(2)bool 为非0[数字0] 其余既1的特性 (这里的0和1都表示正负数数字类型)
bool类型
在C语言标准(c89)并未定义布尔类型,判断数据为0 = 假,非0 = true
在C99开始引入了布尔类型,但是他并不是C语言内置的数据类型。而是C语言通过<stdbool.h> 帮我们实现了对布尔类型数据的判定。头文件如下:
#ifndef _STDBOOL_H
#define _STDBOOL_H
#ifndef __cplusplus
#define bool _Bool
/*这里如果数据为true表示数字1 ,false表示数据0*/
/* 我们在写判断语句的时候,可以直接使用true/false 进行判定是零还是非0来判定 */
/*底层还是通过安段*/
#define true 1
#define false 0
#else /* __cplusplus */
/* Supporting _Bool in C++ is a GCC extension. */
#define _Bool bool
#if __cplusplus < 201103L
/* Defining these macros in C++98 is a GCC extension. */
#define bool bool
#define false false
#define true true
#endif
#endif /* __cplusplus */
/* Signal that all the definitions are present. */
#define __bool_true_false_are_defined 1
#endif /* stdbool.h */
测试代码
#include <stdbool.h>
#include <stdio.h>
int main(){
bool myTrue = true;
bool myFalse = false;
/*
注意:true、false是stdbool内已经帮你做了宏定义
#define true 1
#define false 0
*/
printf("myTrue:%d\n",myTrue); // 1
printf("myFalse:%d\n",myFalse); // 0
/* --------------------------------------- */
// 非0(数字0) 即1
bool myBoolZero = -1; // 1
bool myBoolOne = 1; // 1
bool myChar1 = "-1127"; // 这里是字符串,字符串(不管有无正负号)在编译器看来也是1
bool myChar2 = -996; // 1
bool myChar3 = '0'; // 1
bool myChar4 = 0; // 0
printf("sizeof BOOL myBoolZero size: %d\r\n",sizeof(myBoolZero)); // 1 字节
printf("sizeof BOOL myChar1 size: %d\r\n",sizeof(myChar1)); // 1 字节
printf("myBoolZero:%d\r\n",!myBoolZero); // 0 (这里由于-1被编译器人为是非0数据,则取反的时候,就变成 0 )
printf("myBoolOne:%d,%d\r\n",myBoolOne,!myBoolOne); // 1,0
printf("myChar1 is :%d,%d\r\n",myChar1,!myChar1); // 1,0
printf("myChar2 is :%d,%d\r\n",myChar2,!myChar2); // 1,0
printf("myChar3 is :%d,%d\r\n",myChar3,!myChar3); // 1,0
printf("myChar4 is :%d,%d\r\n",myChar4,!myChar4); // 0,1
/* --------------------------------------- */
/*
总结:
bool 布尔类型使用的,几个规则:
(1)stdbool宏定义了 true = 1,false = 0
(2)bool 为非0[数字0] 其余既1的特性 (这里的0和1都表示正负数数字类型)
*/
return 0;
}
题外话
字(Word)通常是32位,等于4个字节。
半字(Half Word)是16位,等于2个字节。
字节(Byte)是8位。