You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用<stdbool.h>与自定义bool枚举时,两个struct大小不同?

为何两种bool定义方式会导致结构体大小不同?

问题描述

当使用#include <stdbool.h>和typedef enum { false, true } bool;两种方式定义bool类型时,相同的结构体代码会出现不同的大小结果,具体代码及运行情况如下:

代码示例

#include <stdio.h>
#include <stdbool.h>
//typedef enum { false, true } bool;

struct x {
    bool a;
    int b;
    char c;
};

struct y {
    bool b;
    char a;
    int c;
};

int main(void) {

    struct x x;
    struct y y;

    printf("Size of struct x:\t %zu\n", sizeof(x));
    printf("Size of struct y:\t %zu", sizeof(y));

    return 0;
}

运行结果(Mac Intel机器)

  • 使用#include <stdbool.h>时:

    Size of struct x: 12
    Size of struct y: 8

  • 使用typedef enum { false, true } bool;时:

    Size of struct x: 12
    Size of struct y: 12

原因解析

核心差异在于两种方式定义的bool本质是不同类型,大小完全不一样:

  • <stdbool.h>中的bool:这是C99标准引入的原生布尔类型,在Mac Intel的编译环境中,它的大小为1字节(和char类型尺寸相同)。
  • 枚举版的bool:用typedef将枚举类型重命名为bool,C标准规定枚举类型的底层存储大小等同于int(通常为4字节),因为枚举值本质是整数常量。

基于这个差异,结构体的内存布局和填充逻辑发生变化:

  1. 对于<stdbool.h>版本的bool:

    • struct y中,1字节的bool和1字节的char可以连续存放,总共2字节,为了满足int类型的4字节对齐要求,会填充2字节凑到4字节边界,再加上4字节的int,总大小为4+4=8字节。
    • struct x中,1字节的bool需要填充3字节才能对齐到int的4字节边界,加上4字节的int和1字节的char后,又需要填充3字节让整个结构体大小是4字节的倍数,总大小为4+4+4=12字节。
  2. 对于枚举版的bool:

    • 枚举bool大小为4字节,struct y中4字节的bool之后,1字节的char需要填充3字节才能对齐到4字节边界,再加上4字节的int,总大小为4+4+4=12字节,和struct x的布局逻辑一致,因此两者大小相同。

内容的提问来源于stack exchange,提问作者joekash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:16:13