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

2021-12-29 00:00:00 enums c++ sizeof

这是一道 C++ 面试题,不是作业.

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

#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;
 }

输出:

大小月_t是4
y2k 的大小是 4
月份的大小_t1 是 4
y2k1 的大小是 4

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

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

Why is the size of all of these 4 bytes? Not 12 x 4 = 48 bytes?
I know union elements occupy the same memory location, but this is an enum.

推荐答案

大小为四个字节,因为 enum 存储为 int.只有 12 个值,你真的只需要 4 位,但 32 位机器处理 32 位数量比更小数量更有效.

The size is four bytes because the enum is stored as an int. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

0 0 0 0  January
0 0 0 1  February
0 0 1 0  March
0 0 1 1  April
0 1 0 0  May
0 1 0 1  June
0 1 1 0  July
0 1 1 1  August
1 0 0 0  September
1 0 0 1  October
1 0 1 0  November
1 0 1 1  December
1 1 0 0  ** unused **
1 1 0 1  ** unused **
1 1 1 0  ** unused **
1 1 1 1  ** unused **

如果没有枚举,您可能会倾向于使用原始整数来表示月份.这会有效并且有效,但它会使您的代码难以阅读.使用枚举,您可以获得高效的存储和可读性.

Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.

相关文章