C和C++的布尔类型

3 篇文章 0 订阅
2 篇文章 0 订阅

c,c++中的布尔类型使用

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

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

[cpp]  view plain  copy
 print ?
  1. /* 第一种方法 */  
  2. #define TRUE 1  
  3. #define FALSE 0  
  4.   
  5. /* 第二种方法 */   
  6. enum bool{falsetrue};   

2. 使用_Bool

        有了C99标准支持,可以使用 _Bool 来定义布尔型变量。下面是一个例子程序。

[cpp]  view plain  copy
 print ?
  1. #include <stdio.h>   
  2. #include <stdlib.h>    
  3.   
  4. int main(){  
  5.     _Bool a = 1;  
  6.     _Bool b = 2;    /* 使用非零值,b的值为1 */   
  7.     _Bool c = 0;  
  8.     _Bool d = -1;   /* 使用非零值,d的值为1 */   
  9.       
  10.     printf("a==%d,  /n", a);  
  11.     printf("b==%d,  /n", b);  
  12.     printf("c==%d,  /n", c);  
  13.     printf("d==%d,  /n", d);  
  14.   
  15.     printf("sizeof(_Bool) == %d  /n"sizeof(_Bool));  
  16.       
  17.     system("pause");  
  18.     return EXIT_SUCCESS;  
  19. }  

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

[cpp]  view plain  copy
 print ?
  1. a==1,  
  2. b==1,  
  3. c==0,  
  4. d==1,  
  5. sizeof(_Bool) == 1  

3. 使用stdbool.h

        在C++中,通过bool来定义布尔变量,通过truefalse对布尔变量进行赋值。C99为了让我们能够写出与C++兼容的代码,添加了一个头文件<stdbool.h>。在gcc中,这个头文件的源码如下:

[cpp]  view plain  copy
 print ?
  1. /* Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc. 
  2.         This file is part of GCC. 
  3.  */  
  4.   
  5. #ifndef _STDBOOL_H  
  6. #define _STDBOOL_H  
  7.   
  8. #ifndef __cplusplus  
  9.   
  10. #define bool    _Bool  
  11. #define true    1  
  12. #define false   0  
  13.   
  14. #else /* __cplusplus ,应用于C++里,这里不用处理它*/  
  15.   
  16. /* Supporting <stdbool.h> in C++ is a GCC extension.  */  
  17. #define _Bool   bool  
  18. #define bool    bool  
  19. #define false   false  
  20. #define true    true  
  21.   
  22. #endif /* __cplusplus */  
  23.   
  24. /* Signal that all the definitions are present.  */  
  25. #define __bool_true_false_are_defined   1  
  26.   
  27. #endif  /* stdbool.h */  

         可见,stdbool.h中定义了4个宏,bool、true、false、__bool_true_false_are_defined。 其中bool就是 _Bool类型,true和false的值为1和0,__bool_true_false_are_defined的值为1。 
下面是一个例子程序

[cpp]  view plain  copy
 print ?
  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <stdbool.h>  
  4.   
  5. /* 测试C99新添加的头文件 stdbool.h */  
  6.   
  7. int main(){  
  8.     bool m = true;  
  9.     bool n = false;  
  10.     printf("m==%d,  n==%d  /n", m, n);  
  11.       
  12.     printf("sizeof(_Bool) == %d  /n"sizeof(_Bool));  
  13.   
  14.     system("pause");  
  15.     return EXIT_SUCCESS;  
  16. }  

运行结果:

[cpp]  view plain  copy
 print ?
  1. m==1,  n==0  
  2. sizeof(_Bool) == 1  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值