Lesson 8 of 31

Enums

Enums

An enum (enumeration) defines a set of named integer constants. Enums make code more readable by giving meaningful names to numeric values.

Declaration

enum Color {
    RED,     // 0
    GREEN,   // 1
    BLUE     // 2
};

By default, the first constant is 0, and each subsequent one increments by 1.

Starfleet ranks: ENSIGN, LIEUTENANT, COMMANDER, CAPTAIN -- each with a well-defined numeric value.

Using Enums

enum Color c = GREEN;
if (c == GREEN) {
    printf("Green!\n");
}

Custom Values

You can assign specific values:

enum HttpStatus {
    OK = 200,
    NOT_FOUND = 404,
    SERVER_ERROR = 500
};

Enums in Switch

Enums work naturally with switch:

enum Direction { NORTH, SOUTH, EAST, WEST };

void print_direction(enum Direction d) {
    switch (d) {
        case NORTH: printf("North\n"); break;
        case SOUTH: printf("South\n"); break;
        case EAST:  printf("East\n");  break;
        case WEST:  printf("West\n");  break;
    }
}

Enums are Integers

Under the hood, enums are just integers. You can use them in arithmetic and comparisons:

enum Season { SPRING, SUMMER, FALL, WINTER };
int s = SUMMER;  // s == 1

Your Task

Define an enum Season with values SPRING, SUMMER, FALL, WINTER. Write a function int is_warm(enum Season s) that returns 1 if the season is SPRING or SUMMER, and 0 otherwise. Print the result for all four seasons.

TCC compiler loading...
Loading...
Click "Run" to execute your code.