Enumerations: enum
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
enum gives names to a set of integer constants:
enum color { RED, GREEN, BLUE }; // RED = 0, GREEN = 1, BLUE = 2
enum level { LOW = 1, MEDIUM = 5, HIGH = 10 };
enum color c = GREEN;
if (c == GREEN) { ... }
The values go in a row starting from zero unless you set them explicitly. In essence it's an int with clear names: the code if (state == STATE_RUNNING) reads much better than if (state == 2).
enum goes very well with switch. With the -Wall flag, the compiler warns you if you forgot to handle some value:
switch (c) {
case RED: ...; break;
case GREEN: ...; break;
case BLUE: ...; break;
}
A common trick is the last item as a counter: enum { MON, TUE, WED, THU, FRI, SAT, SUN, DAYS_COUNT };.
Task. A traffic light: you're given enum light { RED, YELLOW, GREEN }. Read the current colour as a number and the number of switches k. The colours change in a cycle RED → GREEN → YELLOW → RED. Print the name of the colour after k switches.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.