Using Enums in C++

As with enumerated types in Pascal, using enums in C++ can make your code more readable. We demonstrate how you can cast between an enum variable and an int. By default the first item casts to 0, but you can supply your own numbering as shown for the enum InnerPlanet. The numbering of subsequent items follows on from a supplied value so Mars becomes 4 rather than the default value 3.

The output follows the code.

#include <iostream>

using namespace std;

int main()
{
  enum GasGiant {Jupiter, Saturn, Uranus, Neptune};
  enum InnerPlanet {Mercury = 1, Venus, Earth, Mars};
  GasGiant selectedGasGiant = GasGiant(1);  // casting int to GasGiant

  switch (selectedGasGiant)
  {
    case Jupiter: cout << "Selected gas giant is Jupiter" << endl;
    break;
    case Saturn: cout << "Selected gas giant is Saturn" << endl;
    break;
  }
  cout << "Assigning Jupiter to selectedGasGiant" << endl;
  selectedGasGiant = Jupiter;
  if (int(selectedGasGiant) == 0)  // casting GasGiant to int
    cout << "Current gas giant is Jupiter" << endl;

  cout << "Assigning Mars to selectedInnerPlanet" << endl;
  InnerPlanet selectedInnerPlanet = Mars;
  cout << "Mars is inner planet number " << int(Mars) << endl;

  return 0;
}
    

Output:

Selected gas giant is Saturn
Assigning Jupiter to selectedGasGiant
Current gas giant is Jupiter
Assigning Mars to selectedInnerPlanet
Mars is inner planet number 4
Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++