为什么枚举的大小仅与单个值的大小相对应? [英] Why does the size of enum only correspond to the size of a single value?

查看:42
本文介绍了为什么枚举的大小仅与单个值的大小相对应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章没有答案我的问题.

考虑一下:

enum seq {VAL1, VAL2 = 1000000000, VAL3 = UINT_MAX};

int main(void)
{
    printf("%lu\n", sizeof(enum seq));
}

此处 UINT_MAX uint32_t 的最大值(40亿左右)

Here UINT_MAX is the max value for a uint32_t (4 billion or something)

为什么整个 enum 类型的大小似乎只有4个字节?这仅足以存储一个整数值.

Why is the size of the entire enum type appears to be only 4 bytes? This is only enough to store a single integer value.

推荐答案

我想也许我正在开始理解您的问题.

I think maybe I'm starting to understand your question.

在您的示例程序中,数字 0 1000000000 UINT_MAX 根本不需要存储在程序的内存中,因为您不使用它们.例如,如果您查看其程序集输出,您将看不到任何这些数字.这就是评论说他们无处存储"的意思.

In your example program, the numbers 0, 1000000000 and UINT_MAX do not need to be stored in the program's memory at all, since you do not use them. If for example you look at its assembly output you will not see any of those numbers. That is what the comments mean when they say they are stored "nowhere".

如果您确实使用过它们,很可能会将它们直接编码为一条指令作为立即数,就像您使用整数文字 0 1000000000 4294967295 .例如,参见 https://godbolt.org/z/6YKeE9 .它们也可能会不断折叠(因此,您将不会对数字本身进行编码,而只会对其使用的任何计算结果进行编码),或者完全对其进行编码.但是它们不一定需要存储在数据存储器中,除非您可能使用它们来初始化全局变量或静态变量,例如

If you did use them, they would very likely be encoded directly into an instruction as an immediate, just as if you had used the integer literals 0 or 1000000000 or 4294967295. See for instance https://godbolt.org/z/6YKeE9. They might also be subjected to constant folding (so you wouldn't encode the number itself, only the result of whatever computation it was used in), or optimized out altogether. But they wouldn't necessarily need to be stored in data memory, unless perhaps you used them to initialize a global or static variable, as here.

在C语言中, sizeof(type)始终为您提供该类型的 object 使用的内存量.因此,即使您的编译器确实需要将所有数字 0 1000000000 UINT_MAX 存储在内存中的某个地方, sizeof(enum seq)不会为您提供所需的总内存量;它只会为您提供存储一个类型为 enum seq 的对象所需的内存量.由于4字节无符号整数足够大,可以包含 enum seq 的任何可能值,所以这就是您要得到的大小.

And in C, sizeof(type) always gives you the amount of memory used by an object of that type. So even if you had a compiler that did need to store all of the numbers 0, 1000000000 and UINT_MAX in memory somewhere, sizeof(enum seq) would not give you the total amount of memory needed for that; it would only give you the amount of memory needed to store one object of type enum seq. Since a 4-byte unsigned integer is big enough to contain any one of the possible values of enum seq, that's the size you're getting.

这篇关于为什么枚举的大小仅与单个值的大小相对应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆