C语言中逻辑值真假怎么表示

如题所述

有以下方式:

1、自己定义的“仿布尔型”
在C99标准被支持之前,一般是由开发人员自己模仿定义布尔型,方式有很多种,常见的有下面两种:

/* 第一种方法 */  
#define TRUE 1  
#define FALSE 0  
  
  
/* 第二种方法 */   
enum bool{false, true};

2、使用_Bool

从C99标准开始,可以简单的使用 _Bool 来定义布尔型变量。_Bool类型长度为1,只能取值范围为0或1。将任意非零值赋值给_Bool类型,都会先转换为1,表示真。将零值赋值给_Bool类型,结果为0,表示假。 下面是一个例子程序:

#include <stdio.h>   
#include <stdlib.h>    
  
int main(){  
    _Bool a = 1;  
    _Bool b = 2;    /* 使用非零值,b的值为1 */   
    _Bool c = 0;  
    _Bool d = -1;   /* 使用非零值,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;  
}

3. 使用stdbool.h

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

/* Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc. 
        This file is part of GCC. 
 */  
  
#ifndef _STDBOOL_H  
#define _STDBOOL_H  
  
#ifndef __cplusplus  
  
#define bool    _Bool  
#define true    1  
#define false   0  
  
#else /* __cplusplus ,应用于C++里,这里不用处理它*/  
  
/* Supporting <stdbool.h> 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 */

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

#include <stdio.h>   
#include <stdlib.h>   
#include <stdbool.h>  
  
/* 测试C99新添加的头文件 stdbool.h */  
  
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;  
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-11
非零为真,零表示逻辑假本回答被提问者采纳
相似回答