C语言 stdbool.h啥用

Python015

C语言 stdbool.h啥用,第1张

这是一个头文件,头文件里面定义了许多的函数,使用的一般方法是if

define这样的语法定义的。这是为了方便移植而设计的,比如,常用的scanf,printf这类函数位于头文件stdio.h这个文件里面。而这里,由于需要用到bool(布尔型),所以引用了头文件stdbool.h。因为,bool这个关键字在stdbool.h中定义了得,如果不引用,那么bool就会被编译器视为非法字符,就会出错。

bool 是C++中的关键字,C中不支持

所以C99标准中引入了头文件 stdbool.h,包含了四个用于布尔型的预定义宏

#define true 1

#define false 0

#define bool _Bool

typdef int _Bool

看看 stdbool.h 的内容就知道了。

因为 stdbool.h 头文件是在 C99 标准中引入的,而题主使用的是 Visual C++ 6.0,这款 IDE 是微软在 1998 年发布的,所以内建的编译器不支持 C99 标准,也就不支持导入 stdbool.h 头文件了。由于 VC 6.0 早已过时,所以强烈建议题主更换更新的编译器及开发环境,在 Windows 中可以考虑 MinGW + Notepad++/Atom,Code::Blocks 或者 Visual Studio 2013。如果不想更换开发环境,可以采用以下两种方法来代替 stdbool.h:

使用 1/0 来代替 true/false

#include <stdio.h>

int main() {

    int year

    int leap = 0

    

    scanf("%d", &year)

    

    if (year % 4 == 0) {

        if (year % 100 == 0) {

            if (year % 400 == 0) {

                leap = 1

            } 

        } else {

            leap = 1

        }

    } 

    

    if (leap) 

        printf("%d is a leap year.\n", year)

    else 

        printf("%d is not a leap year.\n", year)

        

    return 0

    

}

或者自己定义一个 bool 类型和 ture/false 变量(本质上和使用 0/1 是一样的)

#include <stdio.h>

#define true 1

#define false 0

typedef int bool

int main() {

    int year

    bool leap = false

    

    scanf("%d", &year)

    

    if (year % 4 == 0) {

        if (year % 100 == 0) {

            if (year % 400 == 0) {

                leap = true

            } 

        } else {

            leap = true

        }

    } 

    

    if (leap) 

        printf("%d is a leap year.\n", year)

    else 

        printf("%d is not a leap year.\n", year)

        

    return 0

    

}