C++ Explicit type conversions Enum conversions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

static_cast can convert from an integer or floating point type to an enumeration type (whether scoped or unscoped), and vice versa. It can also convert between enumeration types.

  • The conversion from an unscoped enumeration type to an arithmetic type is an implicit conversion; it is possible, but not necessary, to use static_cast.
C++11
  • When a scoped enumeration type is converted to an arithmetic type:

    • If the enum's value can be represented exactly in the destination type, the result is that value.
    • Otherwise, if the destination type is an integer type, the result is unspecified.
    • Otherwise, if the destination type is a floating point type, the result is the same as that of converting to the underlying type and then to the floating point type.

    Example:

    enum class Format {
        TEXT = 0,
        PDF = 1000,
        OTHER = 2000,
    };
    Format f = Format::PDF;
    int a = f;                         // error
    int b = static_cast<int>(f);       // ok; b is 1000
    char c = static_cast<char>(f);     // unspecified, if 1000 doesn't fit into char
    double d = static_cast<double>(f); // d is 1000.0... probably
    
  • When an integer or enumeration type is converted to an enumeration type:

    • If the original value is within the destination enum's range, the result is that value. Note that this value might be unequal to all enumerators.
    • Otherwise, the result is unspecified (<= C++14) or undefined (>= C++17).

    Example:

    enum Scale {
        SINGLE = 1,
        DOUBLE = 2,
        QUAD = 4
    };
    Scale s1 = 1;                     // error
    Scale s2 = static_cast<Scale>(2); // s2 is DOUBLE
    Scale s3 = static_cast<Scale>(3); // s3 has value 3, and is not equal to any enumerator
    Scale s9 = static_cast<Scale>(9); // unspecified value in C++14; UB in C++17
    
C++11
  • When a floating point type is converted to an enumeration type, the result is the same as converting to the enum's underlying type and then to the enum type.

    enum Direction {
        UP = 0,
        LEFT = 1,
        DOWN = 2,
        RIGHT = 3,
    };
    Direction d = static_cast<Direction>(3.14); // d is RIGHT
    


Got any C++ Question?