前言
最近发现一个叫OpenJudge的网站,重新温习一下基础的C语言代码,发现bool类型在GCC编译器中无法识别。
一、问题背景
在网站的一个题目中,需要输出bool类型的存储空间大小,bool类型在实际的项目使用中并不常用,但是既然碰到了就看了下解决方法。
二、解决方法
想要编译器识别bool类型可以直接自己定义一个bool类型。
代码如下(示例):
#define TRUE 1
#define FALSE 0
typedef int bool;
既然单独提出来这个数据类型,肯定跟自己定义有所不同,查资料发现,支持C99的编译器中有 stdbool.h 的库函数,包含该头文件,可以直接使用bool类型。该头文件中的定义其实也很简单,下面列出头文件的内容。
区别在于两种方式的bool定义可能不同,所以sizeof算出来的大小可能不一样。
代码如下(示例):
//
// stdbool.h
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The C Standard Library <stdbool.h> header.//
#ifndef _STDBOOL
#define _STDBOOL
#define __bool_true_false_are_defined 1
#ifndef __cplusplus
#define bool _Bool
#define false 0
#define true 1
#endif /* __cplusplus */
#endif /* _STDBOOL */
/*
* Copyright (c) 1992-2010 by P.J. Plauger. ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V5.30:0009 */