what is the size of an enum type data in C++?

前端 未结 8 462
旧巷少年郎
旧巷少年郎 2020-12-01 02:51

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

#include 
using namespace std;
enum months_t { january, february, march, april, may, jun         


        
相关标签:
8条回答
  • 2020-12-01 03:24

    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.

    0 讨论(0)
  • 2020-12-01 03:24

    It depends. The standard only demands that it is large enough to hold all values, so formally an enum like enum foo { zero, one, two }; needs to only be one byte large. However most implementations make those enums as large as ints (that's faster on modern hardware; moreover it's needed for compatibility with C where enums are basically glorified ints). Note however that C++ allows enums with initializers outside of the int range, and for those enums the size will of course also be larger. For example, if you have enum bar { a, b = 1LL << 35 }; then your enum will be larger than 32 bits (most likely 64 bits) even on a system with 32 bit ints (note that in C that enum would not be allowed).

    0 讨论(0)
提交回复
热议问题