bool類型
C99標準以前,C語言沒有定義bool類型,表達式的值0為假窖杀,非0為真。所以條件判斷語句( if(…)入篮、while(…) )非常靈活陈瘦,甚至一個指針類型都可以是條件表達式幌甘。
為了使程序更清晰潮售,我們常常會給出如下的宏定義:
typedef int BOOL;
#define TRUE 1
#define FALSE 0
這是最常見的寫法,能被任何C語言編譯器認可锅风。
C99標準引入了新的關鍵字_Bool
,它是一個關鍵字酥诽,不是宏定義,通過sizeof(_Bool)
得知這個類型占1個字節(jié)皱埠,而且無論給這個類型的變量賦任何非0整數(shù)值肮帐,其值都是1,這也說明了他不是其他整數(shù)類型的別名边器。
為了兼容C++,C99標準引入了一個頭文件stdbool.h
,開發(fā)中我們只要引入這個頭文件训枢,就可以先C++那樣使用bool了。
stdbool.h
頭文件的定義如下
/*===---- stdbool.h - Standard header for booleans -------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===-----------------------------------------------------------------------===
*/
#ifndef __STDBOOL_H
#define __STDBOOL_H
/* Don't define bool, true, and false in C++, except as a GNU extension. */
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool as a GNU extension. */
#define _Bool bool
#if __cplusplus < 201103L
/* For C++98, define bool, false, true as a GNU extension. */
#define bool bool
#define false false
#define true true
#endif
#endif
#define __bool_true_false_are_defined 1
#endif /* __STDBOOL_H */