c - 枚举大小

标签 c enums size enumeration sizeof

有人可以解释为什么成员 X 的大小与枚举类型本身不同,尽管被显式定义为 LL?我需要强制转换完全相同的枚举类型的 (enum e_x)X 成员以确保它具有与类型相同的大小,这似乎违反直觉。

#include <stdio.h>
#include <limits.h>

enum e_x { X = 0LL, M = LLONG_MAX };

int main() {
 printf("%zu %zu %zu %zu\n",
         sizeof X,
         sizeof((enum e_x)X),
         sizeof(enum e_x),
         sizeof(long long));
}

输出:

 4 8 8 8

预期:

 8 8 8 8

当将枚举传递给使用 va_arg 的函数时,您如何处理它?

最佳答案

您期望的行为对于 C++ 是正确的,但不是 C。C 不允许非 int 枚举器。来自 N1570 (~C11) §6.7.2.2/2:

The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.

第 3 段还说:

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.

第 4 段说:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined

sizeof X == sizeof(int) 是 para 3 的结果,大概 sizeof M == 4 也是出于同样的原因。该实现显然为枚举类型选择了 64 位整数类型,因此 sizeof(enum e_x) == 8sizeof((enum e_x)X)) == 8

关于c - 枚举大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17856681/

相关文章:

ios - Swift - Enum 接受一个整数并确定范围

wpf - 如何在 WPF 中找到任意字形的精确大小?

响应 AT 调制解调器,缓冲区数组中的检查值为 0 且不为 NULL?

c - C 中的 WinAPI 文本输出

c# - 创建丰富枚举的想法

java - Java 中的枚举和泛型

html - 如何在浏览器窗口较小的情况下均匀间隔三张图片,并避免它们重叠?

c++ - 将未知大小的二维数组传递给函数 C++

c - 我能够同时在两个不同的进程中访问/dev/ttyS0设备文件。为什么?

c - Linux内核模块不自动加载