enum

An enum is a special type that holds named constants.

They syntax is:

enum color {red, green, blue};

By default, the data types are int and the first value is 0.

You can also create a scoped enum, as:

enum class color {red, green, blue};

and then you would access the data as color::red, …

A common use case is to provide integer names to indices that are physically meaningful. For example, imagine that we have a 2D array of data that has N positions and M quantities at each position:

Listing 64 enum_components.cpp
#include <iostream>
#include <vector>
#include <array>

enum field  {density, momentum, energy, ncomp};

int main() {

    std::array<std::array<double, ncomp>, 10> data{};

    for (auto & state : data) {
        state[density] = 1.0;
        state[momentum] = 2.0;
        state[energy] = 0.5 * state[momentum] * state[momentum] / state[density];
    }

    std::cout << "number of states = " << data.size() << std::endl;

    std::cout << data[3][density] << " "
          << data[3][momentum] << " "
          << data[3][energy] << std::endl;

}