what is the size of an enum type data in C++?(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;
}
输出:
大小月_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.
这篇关于C++ 中枚举类型数据的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中枚举类型数据的大小是多少?
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
