C ++中枚举类型数据的大小是多少? [英] what is the size of an enum type data in C++?

查看:546
本文介绍了C ++中枚举类型数据的大小是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个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;
 }

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

why the all size is 4 bytes ? not 12 x 4 = 48 bytes ? I know union elements occupy the same memory location, but this is 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.

这篇关于C ++中枚举类型数据的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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