不同编译器的枚举大小(以字节为单位)

发布于 2024-12-03 12:24:52 字数 88 浏览 2 评论 0原文

枚举的大小在不同编译器(gcc、Visual C 等?)中始终相同。也就是说,特定枚举的 sizeof() 是否为每个遵循 C/C++ 标准的编译器提供相同的值?

is the size of an enum always the same among different compilers (gcc, visual c and others?). That is, does sizeof() of a specific enum gives the same values with every compiler that follow the C/C++ standards?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饭团 2024-12-10 12:24:52

不会。

在 C 和 C++ 中,枚举的大小使得所有值都可以表示并与整数类型兼容。不同的编译器可能使用不同的算法来选择类型(如果没有由另一个标准指定,例如明确定义的 ABI)。 (C++11 允许使用新语法指定底层类型)

No.

In both C and C++ an enum will have a size such that all the values can be represented and be compatible with an integer type. Different compilers may use different algorithm to choose the type (if it is not specified by another standard such a clearly defined ABI). (C++11 allows to specify the underlying type with a new syntax)

时光无声 2024-12-10 12:24:52

“每个枚举类型都应与 char(有符号的)兼容”
整数类型,或无符号整数类型。类型的选择是
实现定义)但应能够代表
枚举所有成员的值。”

“...实现可能会延迟选择哪种整数类型
直到看到所有枚举常量。”

ISO/IEC 9899:1999 (E) p.105

所以我们只有 sizeof(enum) 的上限。在大多数系统上,我有 sizeof(enum) = 4,但 STM 编译器使 sizeof (enum) = 1/2/4 取决于枚举中写入的值

编辑:似乎您可以将枚举的值之一设置为 max int 以确保编译器选择整数作为枚举 尺寸。

"Each enumerated type shall be compatible with char, a signed
integer type, or an unsigned integer type. The choice of type is
implementation-defined) but shall be capable of representing the
values of all the members of the enumeration."

"...An implementation may delay the choice of which integer type
until all enumeration constants have been seen."

ISO/IEC 9899:1999 (E) p.105

So we only have upper boundaries for sizeof(enum). On most systems i had sizeof(enum) = 4, but STM compiler made sizeof(enum) = 1/2/4 depending on values written in enum

Edit: it seems that you can set one of your enum's value to max int to ensure that compiler chooses integer as enum size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文