What is the underlying type of a c++ enum?

后端 未结 3 1426
感动是毒
感动是毒 2020-11-30 03:18

This may have been answered elsewhere but I could not find a suitable response.

I have this code:

enum enumWizardPage
{
    WP_NONE = 0x00,  
    WP_         


        
相关标签:
3条回答
  • 2020-11-30 03:27

    IIRC its represented as int in memory. But gcc has switch -fshort-enum to make it a shortest integer type that fits all the values, if you need to save space. Other compilers will have something similar.

    0 讨论(0)
  • 2020-11-30 03:28

    From N4659 C++ 7.2/5:

    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. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.

    0 讨论(0)
  • 2020-11-30 03:31

    The type of a C++ enum is the enum itself. Its range is rather arbitrary, but in practical terms, its underlying type is an int.

    It is implicitly cast to int wherever it's used, though.

    C++11 changes

    This has changed since C++11, which introduced typed enums. An untyped enum now is defined as being at least the width of int (and wider if larger values are needed). However, given a typed enum defined as follows:

    enum name : type {};
    

    An enumeration of type name has an underlying type of type. For example, enum : char defines an enum the same width as char instead of int.

    Further, an enum can be explicitly scoped as follows:

    enum class name : type {
        value = 0,
        // ...
    };
    

    (Where name is required, but type is optional.) An enum declared this way will no longer implicitly cast to its underlying type (requiring a static_cast<>) and values must be referenced with a fully-qualified name. In this example, to assign value to a enum variable, you must refer to it as name::value.

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