c: bool

有人說c語言中沒有bool類型,只有c++中有,果真如此?

1 先看沒有bool類型時,c中表示bool類型的方法:

typedef int bool;
#define false 0
#define true 1
2、

typedef int bool;
enum { false, true };
3、

typedef enum { false, true }bool;


也許很多人都和我一樣,不知道現在的C語言已經有了布爾型:從C99標準開始,類型名字爲“_Bool”。

    在此之前的C語言中,使用整型int來表示真假。在輸入時:使用非零值表示真;零值表示假。在輸出時:真的結果是1,假的結果是0;(這裏我所說的“輸入”,意思是:當在一個需要布爾值的地方,也就是其它類型轉化爲布爾類型時,比如 if 條件判斷中的的條件;“輸出”的意思是:程序的邏輯表達式返回的結果,也就是布爾類型轉化爲其他類型時,比如 a==b的返回結果,只有0和1兩種可能)。

    所以,現在只要你的編譯器支持C99(我使用的是Dev C++4.9.9.2),你就可以直接使用布爾型了。另外,C99爲了讓C和C++兼容,增加了一個頭文件stdbool.h。裏面定義了bool、true、false,讓我們可以像C++一樣的定義布爾類型。
  1. 我們自己定義的“仿布爾型”
    在C99標準被支持之前,我們常常自己模仿定義布爾型,方式有很多種,常見的有下面兩種:

/* 第一種方法 */
#define TRUE 1
#define FALSE 0

/* 第二種方法 */
enum bool{false, true};
2. 使用_Bool
現在,我們可以簡單的使用 _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;

}
運行結果如下:(只有0和1兩種取值)

a1,
b
1,
c0,
d
1,
sizeof(_Bool) == 1
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 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章