How to change the integer type used by an enum C++

In this blog post, you will learn how to change the integer type used by an enum C++. One point you should remember is that what I will explain here only applies to C++11 or above. You cannot do this in C++98/03.

So without wasting time let us see a syntax to how we can change the integer type used by an enum.

//1. Unscoped enum:
enum[identifier][:type]
{
  enum-list

};



//2. Scoped enum:
enum [class|struct] [identifier] [:type]
{
  enum-list

};

Where,

identifier: The type name given to the enumeration.

type: The underlying type of the enumerators.

enum-list: Comma-separated list of the enumerators in the enumeration.

class/struct: By using the class or struct keyword in the declaration, you specify the enum is scoped.

 

Now it is time to see the example code to understand the above concepts.

#include <iostream>

   using namespace std;

   enum ETest1 : uint8_t
   {
      eA = 1,
      eB,
      eC
   };

   enum ETest2 : uint16_t
   {
      eD = 1,
      eE,
      eF
   };

   enum ETest3 : uint32_t
   {
      eG = 1,
      eH,
      eI
   };

   int main()
   {
      cout << "Size of ETest1 = " << sizeof(ETest1) << endl;

      cout << "Size of ETest2 = " << sizeof(ETest2) << endl;

      cout << "Size of ETest3 = " << sizeof(ETest3) << endl;

      return 0;
   }

Output:

Size of ETest1 = 1
Size of ETest2 = 2
Size of ETest3 = 4

 

Recommended Post