Lesson 111 +10 XP

Enums

An enum (short for enumeration) turns a set of choices into named values for a variable. Instead of remembering which number stood for "LSpeed" or "High", you name them.

Introducing an enum


cpp
#include <iostream>
using namespace std;

enum Level {

### LOW,

### MEDIUM,

### HIGH
};
  • enum starts the definition.
  • Level is the name of the new type.
  • LOW, MEDIUM, HIGH are the named values (enumerators).

Declaring an enum variable


cpp
int main() {

### Level myLevel = MEDIUM;
  // ...
  return 0;
}

myLevel can be any of the three values, and you can compare it later.

Switching on an enum


cpp
int main() {
  Level myLevel = MEDIUM;

switch (myLevel) {
    case 0:
      cout << "Low Level" << endl;
      break;
    case 1:
      cout << "Medium Level" << endl;
      break;
    case 2:
      cout << "High Level" << endl;
      break;
  }
  return 0;
}

The default numbering

Unless you say otherwise, enumerators get the numbers 0, 1, 2, ... in the order you list them. So LOW = 0, MEDIUM = 1, HIGH = 2.

Explicit values

You can assign the numbers yourself:


cpp
enum Level {

### LOW = 25,

### MEDIUM = 50,

### HIGH = 75
};

Pick explicit numbers when the values must line up with data or settings from somewhere else.

TL;DR

  • enum Name { value1, value2, ... }; defines a named set of values.
  • Enumerators default to 0, 1, 2, ... in the order you list them.
  • Use it in a switch, in comparisons, and in functions.
  • You can override numbers by hand: LOW = 25.
  • Enums turn magic numbers into readable names.