Skip to content

C 标准库 - <stdbool.h>

概述

<stdbool.h> 头文件定义了布尔类型和相关宏,使得在 C 语言中使用布尔值更加方便和直观。这是 C99 标准引入的头文件。

布尔类型

bool

布尔类型,可以存储 truefalse 值。

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

int main() {
    bool flag = true;
    
    if (flag) {
        printf("flag 为真\n");
    } else {
        printf("flag 为假\n");
    }
    
    return 0;
}

布尔常量

true

表示真值的宏。

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

int main() {
    bool is_valid = true;
    
    printf("is_valid = %d\n", is_valid);
    
    return 0;
}

false

表示假值的宏。

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

int main() {
    bool is_valid = false;
    
    printf("is_valid = %d\n", is_valid);
    
    return 0;
}

布尔宏

__bool_true_false_are_defined

定义为 1 的宏,表示 truefalse 已定义。

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

int main() {
    printf("__bool_true_false_are_defined = %d\n", 
           __bool_true_false_are_defined);
    
    return 0;
}

实际应用示例

1. 简单的布尔逻辑

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

int main() {
    bool a = true;
    bool b = false;
    
    printf("a = %d\n", a);
    printf("b = %d\n", b);
    printf("a && b = %d\n", a && b);
    printf("a || b = %d\n", a || b);
    printf("!a = %d\n", !a);
    
    return 0;
}

2. 条件判断

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

bool is_even(int number) {
    return number % 2 == 0;
}

bool is_positive(int number) {
    return number > 0;
}

int main() {
    int num = 10;
    
    if (is_even(num)) {
        printf("%d 是偶数\n", num);
    } else {
        printf("%d 是奇数\n", num);
    }
    
    if (is_positive(num)) {
        printf("%d 是正数\n", num);
    } else {
        printf("%d 不是正数\n", num);
    }
    
    return 0;
}

3. 用户验证

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

bool validate_username(const char* username) {
    return strlen(username) >= 3 && strlen(username) <= 20;
}

bool validate_password(const char* password) {
    return strlen(password) >= 8;
}

bool login(const char* username, const char* password) {
    const char* valid_username = "admin";
    const char* valid_password = "password123";
    
    return strcmp(username, valid_username) == 0 && 
           strcmp(password, valid_password) == 0;
}

int main() {
    char username[50];
    char password[50];
    
    printf("用户名: ");
    scanf("%s", username);
    
    printf("密码: ");
    scanf("%s", password);
    
    if (!validate_username(username)) {
        printf("用户名长度必须在 3-20 个字符之间\n");
        return 1;
    }
    
    if (!validate_password(password)) {
        printf("密码长度必须至少 8 个字符\n");
        return 1;
    }
    
    if (login(username, password)) {
        printf("登录成功!\n");
    } else {
        printf("用户名或密码错误\n");
    }
    
    return 0;
}

4. 数组搜索

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

bool contains(int arr[], int size, int value) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == value) {
            return true;
        }
    }
    return false;
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    int search_value = 3;
    
    if (contains(numbers, size, search_value)) {
        printf("%d 在数组中\n", search_value);
    } else {
        printf("%d 不在数组中\n", search_value);
    }
    
    return 0;
}

5. 状态标志

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

typedef struct {
    bool is_running;
    bool is_paused;
    bool is_finished;
} GameState;

void update_game(GameState* state) {
    if (state->is_running && !state->is_paused) {
        printf("游戏运行中...\n");
    } else if (state->is_paused) {
        printf("游戏已暂停\n");
    } else if (state->is_finished) {
        printf("游戏已结束\n");
    }
}

int main() {
    GameState game = {true, false, false};
    
    update_game(&game);
    
    game.is_paused = true;
    update_game(&game);
    
    game.is_paused = false;
    game.is_finished = true;
    game.is_running = false;
    update_game(&game);
    
    return 0;
}

6. 输入验证

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

bool is_valid_email(const char* email) {
    bool has_at = false;
    bool has_dot = false;
    
    for (int i = 0; email[i] != '\0'; i++) {
        if (email[i] == '@') {
            has_at = true;
        } else if (email[i] == '.') {
            has_dot = true;
        }
    }
    
    return has_at && has_dot;
}

bool is_valid_phone(const char* phone) {
    for (int i = 0; phone[i] != '\0'; i++) {
        if (!isdigit(phone[i])) {
            return false;
        }
    }
    return true;
}

int main() {
    char email[100];
    char phone[20];
    
    printf("邮箱: ");
    scanf("%s", email);
    
    printf("电话: ");
    scanf("%s", phone);
    
    if (is_valid_email(email)) {
        printf("邮箱格式正确\n");
    } else {
        printf("邮箱格式错误\n");
    }
    
    if (is_valid_phone(phone)) {
        printf("电话格式正确\n");
    } else {
        printf("电话格式错误\n");
    }
    
    return 0;
}

7. 权限检查

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

typedef struct {
    bool can_read;
    bool can_write;
    bool can_execute;
} Permissions;

bool has_permission(Permissions perms, const char* action) {
    if (strcmp(action, "read") == 0) {
        return perms.can_read;
    } else if (strcmp(action, "write") == 0) {
        return perms.can_write;
    } else if (strcmp(action, "execute") == 0) {
        return perms.can_execute;
    }
    return false;
}

int main() {
    Permissions user_perms = {true, false, false};
    Permissions admin_perms = {true, true, true};
    
    printf("用户权限:\n");
    printf("  读取: %d\n", has_permission(user_perms, "read"));
    printf("  写入: %d\n", has_permission(user_perms, "write"));
    printf("  执行: %d\n", has_permission(user_perms, "execute"));
    
    printf("\n管理员权限:\n");
    printf("  读取: %d\n", has_permission(admin_perms, "read"));
    printf("  写入: %d\n", has_permission(admin_perms, "write"));
    printf("  执行: %d\n", has_permission(admin_perms, "execute"));
    
    return 0;
}

8. 数据验证

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

bool is_valid_age(int age) {
    return age >= 0 && age <= 150;
}

bool is_valid_score(int score) {
    return score >= 0 && score <= 100;
}

bool is_valid_year(int year) {
    return year >= 1900 && year <= 2100;
}

int main() {
    int age = 25;
    int score = 95;
    int year = 2024;
    
    if (is_valid_age(age)) {
        printf("年龄 %d 有效\n", age);
    } else {
        printf("年龄 %d 无效\n", age);
    }
    
    if (is_valid_score(score)) {
        printf("分数 %d 有效\n", score);
    } else {
        printf("分数 %d 无效\n", score);
    }
    
    if (is_valid_year(year)) {
        printf("年份 %d 有效\n", year);
    } else {
        printf("年份 %d 无效\n", year);
    }
    
    return 0;
}

9. 字符串比较

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

bool strings_equal(const char* str1, const char* str2) {
    return strcmp(str1, str2) == 0;
}

bool string_contains(const char* str, const char* substr) {
    return strstr(str, substr) != NULL;
}

bool string_starts_with(const char* str, const char* prefix) {
    return strncmp(str, prefix, strlen(prefix)) == 0;
}

int main() {
    const char* str1 = "Hello, World!";
    const char* str2 = "Hello, World!";
    const char* str3 = "Hello";
    
    printf("str1 == str2: %d\n", strings_equal(str1, str2));
    printf("str1 包含 'World': %d\n", string_contains(str1, "World"));
    printf("str1 以 'Hello' 开头: %d\n", string_starts_with(str1, str3));
    
    return 0;
}

10. 配置选项

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

typedef struct {
    bool debug_mode;
    bool verbose_output;
    bool log_to_file;
    bool auto_save;
} Config;

void print_config(const Config* config) {
    printf("配置选项:\n");
    printf("  调试模式: %d\n", config->debug_mode);
    printf("  详细输出: %d\n", config->verbose_output);
    printf("  日志文件: %d\n", config->log_to_file);
    printf("  自动保存: %d\n", config->auto_save);
}

int main() {
    Config config = {
        .debug_mode = true,
        .verbose_output = false,
        .log_to_file = true,
        .auto_save = true
    };
    
    print_config(&config);
    
    return 0;
}

与其他类型的转换

整数转布尔

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

int main() {
    int num = 42;
    bool flag = (bool)num;
    
    printf("num = %d\n", num);
    printf("flag = %d\n", flag);
    
    return 0;
}

布尔转整数

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

int main() {
    bool flag = true;
    int num = (int)flag;
    
    printf("flag = %d\n", flag);
    printf("num = %d\n", num);
    
    return 0;
}

指针转布尔

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

int main() {
    int value = 42;
    int* ptr = &value;
    int* null_ptr = NULL;
    
    bool has_value = (bool)ptr;
    bool is_null = (bool)null_ptr;
    
    printf("has_value = %d\n", has_value);
    printf("is_null = %d\n", is_null);
    
    return 0;
}

注意事项

1. 布尔值的输出

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

int main() {
    bool flag = true;
    
    printf("flag = %d\n", flag);
    printf("flag = %s\n", flag ? "true" : "false");
    
    return 0;
}

2. 布尔值的比较

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

int main() {
    bool a = true;
    bool b = true;
    
    if (a == b) {
        printf("a 和 b 相等\n");
    }
    
    if (a) {
        printf("a 为真\n");
    }
    
    return 0;
}

3. 避免整数混淆

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

int main() {
    bool flag = 2;
    
    if (flag) {
        printf("flag 为真\n");
    }
    
    printf("flag 的值: %d\n", flag);
    
    return 0;
}

4. 布尔运算符

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

int main() {
    bool a = true;
    bool b = false;
    
    printf("a && b = %d\n", a && b);
    printf("a || b = %d\n", a || b);
    printf("!a = %d\n", !a);
    printf("!b = %d\n", !b);
    
    return 0;
}

总结

<stdbool.h> 提供的布尔类型和相关宏使 C 语言中的布尔操作更加直观和易读:

  1. 简单直观 - 使用 truefalse 代替 1 和 0
  2. 提高可读性 - 代码更容易理解和维护
  3. 类型安全 - 明确的布尔类型
  4. 广泛使用 - 适用于各种需要布尔值的场景

记住:

  • true 实际上是宏,值为 1
  • false 实际上是宏,值为 0
  • 布尔值可以与整数相互转换
  • 使用布尔类型可以提高代码的可读性
  • 在条件判断中直接使用布尔变量