Chinaunix首页 | 论坛 | 博客
  • 博客访问: 594935
  • 博文数量: 66
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1810
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-23 13:53
个人简介

linux

文章分类

全部博文(66)

文章存档

2016年(1)

2015年(14)

2014年(32)

2013年(19)

分类: LINUX

2013-07-27 20:15:34

在此之前的C语言中,使用整型int来表示真假。在输入时:使用非零值表示真;零值表示假。在输出时:真的结果是1,假的结果是0;(这里我所说的“输入”,意思是:当在一个需要布尔值的地方,也就是其它类型转化为布尔类型时,比如 if 条件判断中的的条件;“输出”的意思是:程序的逻辑表达式返回的结果,也就是布尔类型转化为其他类型时,比如 a==b的返回结果,只有0和1两种可能)。

        所以,现在只要你的编译器支持C99,你就可以直接使用布尔型了。另外,C99为了让CC++兼容,增加了一个头文件stdbool.h。里面定义了booltruefalse,让我们可以像C++一样的定义布尔类型。


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

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


点击(此处)折叠或打开

  1. /* 第一种方法 */
  2. #define TRUE 1
  3. #define FALSE 0
  4.   
  5.   
  6. /* 第二种方法 */
  7. enum bool{false, true}

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


点击(此处)折叠或打开

  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 */

下面是一个例子程序

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>

  4. int main()
  5. {
  6.   bool m = true;
  7.   bool n = false;

  8.   printf("m==%d, n==%d\n",m,n);
  9.   exit(0);
  10. }

执行结果为:

点击(此处)折叠或打开

  1. m==1, n==0
http://http://blog.csdn.net/daheiantian/article/details/6241893





阅读(11628) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~