C++ Core Guidelines: Rules for Enumerations

The section to enumerations has eight rules. Since C++11, we have scoped enumerations which overcome a lot of the drawbacks of classical enumerations. 

 

hand 162127 640

Enumerations are sets of integer values, which behave like a type. Here is the summary of the rules:

As I mentioned it in the opening to this post: classical enumerations have a lot of drawbacks. Let me explicitly compare classical (unscoped) enumerations and scoped enumerations (sometimes called strongly typed enumerations), because this important comparison is not explicitly described in the rules.

Here is a classical enumeration:

enum Colour{
  red,
  blue,
  green
};

 

Here are the drawbacks of the classical enumerations:

  • The enumerators have no scope
  • The enumerators implicitly convert to implicitly to int
  • The enumerators pollute the global namespace
  • The type of the enumerator is not defined. It just has to be big enough to hold the enumerator.

By using the keyword class or struct, the classical enumeration becomes a scoped enumeration (enum class):

enum class ColourScoped{
  red,
  blue,
  green
};

 

Now, you have to use the scope operator for accessing the enumerators: ColourScoped::red. ColourScoped::red will not implicitly convert to int and will, therefore, not pollute the global namespace. Additionally, the underlying type is per default int. 

After providing the background information we can directly jump into the rules.

Enum.1: Prefer enumerations over macros

Macros don't respect a scope and have no type. This means you can override a previously set macro which specifies a colour.

// webcolors.h 
#define RED   0xFF0000

// productinfo.h
#define RED    0

int webcolor = RED;   // should be 0xFF0000

 

With ColourScoped this will not happen because you have to use the scope operator: ColourScoped webcolour = ColourScoped::red;

This rule is quite obvious because the enumerators are a set of integers which create a kind of a type.  

Enum.3: Prefer enum classes over “plain” enums

The enumerators of a scoped enum (enum class) will not automatically convert to int. You have to access them with the scope operator.

// scopedEnum.cpp

#include <iostream>

enum class ColourScoped{
  red,
  blue,
  green
};

void useMe(ColourScoped color){

  switch(color){
  case ColourScoped::red:
    std::cout << "ColourScoped::red" << std::endl;
    break;
  case ColourScoped::blue:
    std::cout << "ColourScoped::blue" << std::endl;
    break;
  case ColourScoped::green:
    std::cout << "ColourScoped::green" << std::endl;
    break;
  }
}

int main(){

  std::cout <<  static_cast<int>(ColourScoped::red) << std::endl;   // 0
  std::cout <<  static_cast<int>(ColourScoped::red) << std::endl;   // 0

  std::cout << std::endl;

  ColourScoped colour{ColourScoped::red};
  useMe(colour);                                                     // ColourScoped::red

}

 

Enum.4: Define operations on enumerations for safe and simple use

The rules define an enumeration Day which supports the increment operation.

enum Day { mon, tue, wed, thu, fri, sat, sun };

Day& operator++(Day& d)
{
    return d = (d == Day::sun) ? Day::mon : static_cast<Day>(static_cast<int>(d)+1);
}

Day today = Day::sat;
Day tomorrow = ++today;

 

The static_cast is necessary in this example because applying the increment operator inside the increment operator would cause an infinite recursion:

Day& operator++(Day& d)
{
    return d = (d == Day::sun) ? Day::mon : Day{++d};    // error
}

 

Enum.5: Don’t use ALL_CAPS for enumerators

If you use ALL_CAPS for enumerators, you may get a conflict with macros because they are typically written in ALL_CAPS.

#define RED 0xFF0000

enum class ColourScoped{ RED };  // error

Enum.6: Avoid unnamed enumerations

If you can't find a name for the enumerations, the enumerations may be not related. In this case, you should use a constexpr value.

// bad
enum { red = 0xFF0000, scale = 4, is_signed = 1 };

// good
constexpr int red = 0xFF0000;
constexpr short scale = 4;
constexpr bool is_signed = true;

Enum.7: Specify the underlying type of an enumeration only when necessary

Since C++11, you can specify the underlying type of the enumeration and save memory. Per default the type of a scoped enum is int and, therefore, you can forward declare an enum.

// typeEnum.cpp

#include <iostream>

enum class Colour1{
  red,
  blue,
  green
};
 
enum struct Colour2: char {
  red,
  blue,
  green
};

int main(){

  std::cout << sizeof(Colour1) << std::endl;  // 4
  std::cout << sizeof(Colour2) << std::endl;  // 1

}

Enum.8: Specify enumerator values only when necessary

By specifying the enumerator values it may happen that you set a value twice. The following enumeration Col2 has this issue.

enum class Col1 { red, yellow, blue };
enum class Col2 { red = 1, yellow = 2, blue = 2 };    // typo
enum class Month { jan = 1, feb, mar, apr, may, jun,
                   jul, august, sep, oct, nov, dec }; // starting with 1 is conventional

 

What's next?

I made it relatively short in this post. The meta-rule that you should have to keep in mind is: use scoped enums.

The next section of the C++ core guidelines deals with about 35 rules to resource management. This means we dive in the next post right into the heart of C++.

 

 

Thanks a lot to my Patreon Supporters: Eric Pederson, Paul Baxter, and Franco Amato.

 

Get your e-book at leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 550 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Add comment


My Newest E-Books

Latest comments

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 875

All 538596

Currently are 181 guests and no members online