天天看點

整型與布爾型的轉換c語言,C語言的布爾類型(_Bool)【轉】

該樓層疑似違規已被系統折疊 隐藏此樓檢視此樓

1. 我們自己定義的“仿布爾型”

在C99标準被支援之前,我們常常自己模仿定義布爾型,方式有很多種,常見的有下面兩種:

view plaincopy to clipboardprint?

#define TRUE 1

#define FALSE 0

enum bool{false, true};

2. 使用_Bool

現在,我們可以簡單的使用 _Bool 來定義布爾型變量。_Bool類型長度為1,隻能取值範圍為0或1。将任意非零值指派給_Bool類型,都會先轉換為1,表示真。将零值指派給_Bool類型,結果為0,表示假。 下面是一個例子程式。

view plaincopy to clipboardprint?

#include 

#include 

int main(){

_Bool a = 1;

_Bool b = 2;    

_Bool c = 0;

_Bool 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兩種取值)

view plaincopy to clipboardprint?

a==1,

b==1,

c==0,

d==1,

sizeof(_Bool) == 1

3. 使用stdbool.h

在C++中,通過bool來定義布爾變量,通過true和false對布爾變量進行指派。C99為了讓我們能夠寫出與C++相容的代碼,添加了一個頭檔案。在gcc中,這個頭檔案的源碼如下:(注,為了清楚,不重要的注釋部分已經省略)

view plaincopy to clipboardprint?

/* Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.

This file is part of GCC.