C 语言中,虽然没有内置的 bool 类型(在 C90 标准中),但仍然需要表示真(true)和假(false)的值。为了在 C 语言中处理布尔值,程序员通常使用整数类型,因为 C 语言中的 0 表示假(false),而非零的值表示真(true)。但是,从 C99 开始,C 标准引入了 stdbool.h 头文件,这使得处理布尔值变得更加简便。

1、C99 之前的方法

在 C99 标准之前,C 语言没有内建的布尔类型。开发者通常采用以下替代方法。

1) 使用 typedef 配合 #define 宏定义

#include <stdio.h>

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

int main() {
    bool isEven = true;
    int num = 4;

    // 使用自定义的 bool 类型进行判断
    if (isEven && num % 2 == 0) {
        printf("The number %d is even.\n", num);
    } else {
        printf("The number %d is odd.\n", num);
    }

    // 修改 isEven 的值
    isEven = false;
    if (!isEven) {
        printf("isEven is now false.\n");
    }

    return 0;
}

2)使用 typedef 中的 enum 枚举类型

#include <stdio.h>

typedef int bool;
enum { false, true };  // false = 0, true = 1

int main() {
    bool isActive = true;
    bool isCompleted = false;

    if (isActive) {
        printf("The task is active.\n");
    } else {
        printf("The task is not active.\n");
    }

    if (isCompleted) {
        printf("The task is completed.\n");
    } else {
        printf("The task is not completed.\n");
    }

    return 0;
}

3)显式地将 typedef 与 enum 结合

#include <stdio.h>

// 定义布尔类型
typedef enum { false, true } bool;

int main() {
    bool isActive = true;
    bool isFinished = false;

    // 使用布尔类型的值
    if (isActive) {
        printf("The process is active.\n");
    }

    if (!isFinished) {
        printf("The process is not finished yet.\n");
    }

    return 0;
}

2、C99 及更高版本

C99 标准引入了 头文件,定义了 bool 作为 _Bool(内建类型)的宏。truefalse 分别作为 10 的宏。

#include <stdio.h>
#include <stdbool.h>

int main() {
    bool flag = true;  // 定义一个布尔类型变量并初始化为 true

    // 根据 flag 的值执行不同的操作
    if (flag) {
        printf("Flag is true!\n");
    } else {
        printf("Flag is false!\n");
    }

    // 修改 flag 的值为 false
    flag = false;

    // 再次判断 flag 的值
    if (flag) {
        printf("Flag is true!\n");
    } else {
        printf("Flag is false!\n");
    }

    return 0;
}