c++ - C++中枚举类型数据的大小是多少?

标签 c++ enums sizeof

这是一道 C++ 面试题,不是家庭作业。

#include <iostream>
using namespace std;
enum months_t { january, february, march, april, may, june, july, august, september,    
  october, november, december} y2k;

 int main ()
  {
    cout << "sizeof months_t is  " << sizeof(months_t) << endl;
    cout << "sizeof y2k is  " << sizeof(y2k) << endl;
    enum months_t1 { january, february, march, april, may, june, july, august,    
       september, october, november, december} y2k1;
    cout << "sizeof months_t1 is  " << sizeof(months_t1) << endl;
    cout << "sizeof y2k1 is  " << sizeof(y2k1) << endl;
 }

输出:

sizeof months_t is 4
sizeof y2k is 4
sizeof months_t1 is 4
sizeof y2k1 is 4

为什么所有这 4 个字节的大小都是如此?不是 12 x 4 = 48 字节?
我知道 union 元素占用相同的内存位置,但这是一个枚举。

最佳答案

This is a C++ interview test question not homework.

那么你的面试官需要用 C++ 标准的工作原理来刷新他的记忆。 And I quote :

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.

整个“其底层类型不固定”部分来自C++11,但其余部分都是标准C++98/03。简而言之,sizeof(months_t)not 4。它也不是 2。 可能是其中任何一个。该标准没有说明它应该是什么尺寸;只是它应该足够大以容纳任何枚举器。

why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?

因为枚举不是变量。枚举的成员不是实际变量;它们只是#define 的半类型安全形式。它们是以易于阅读的格式存储数字的一种方式。编译器会将枚举器的所有用途转换为实际的数值。

枚举器只是谈论数字的另一种方式。 january 只是 0 的简写。 0占用多少空间?这取决于您将其存储在什么位置。

关于c++ - C++中枚举类型数据的大小是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115550/

相关文章:

c++ - 在cppcms GET或POST请求中显示参数

c++ - LNK2001 : Unresolved external symbol when using qwt plot in Qt creator

c++ - 在头文件中使用一个类作为另一个类中的值类型

enums - Flutter/Dart 将 Int 转换为 Enum

python - 如何在数据库(MYSQL)中保留VARCHAR,但在sqlalchemy模型中保留ENUM

python - 获取填充字典的大小

c++ - 使用多个头文件和 cpp 文件帮助

c# - 绑定(bind)到 xaml 中枚举的显示名称属性

c - sizeof(table)/sizof(table[0]) 不起作用

c - 不带 () 的 sizeof 有什么作用?