Course contentsShow
← C
Lesson 662 of 1,2199. Structures and UnionsFree lesson

Default integer values in enums

Default integer values in enums

What you'll learn: How C automatically assigns incrementing numerical values to your list of named constants.

The automatic scoreboard

In the previous lesson, we learned that an enum lets you create a list of human-readable names. While these names look like words to you, the C compiler treats them as integers. The most important thing to understand is that if you don't manually assign numbers to these names, C does it for you using a very simple rule: it starts at zero and counts up by one.

Think of it like a deli counter ticket system. When the first person walks in, they get number 0. The next person gets 1, the next gets 2, and so on. Even if you don't print the numbers on the tickets, the order remains fixed.

Starting from zero

By default, the first identifier in your enumeration is assigned the value 0. Each subsequent name is assigned a value that is one greater than the one before it.

#include <stdio.h>

enum TrafficLight {
    GREEN,  // Assigned 0
    YELLOW, // Assigned 1
    RED     // Assigned 2
};

int main() {
    enum TrafficLight signal = RED;

    // This will print "The value of RED is 2"
    printf("The value of RED is %d\n", signal);

    if (signal == 2) {
        printf("The light is mathematically RED.");
    }

    return 0;
}

In this example, even though we never typed = 0 or = 2, C handled the math behind the scenes. GREEN is the "0-th" item, YELLOW is 1, and RED is 2.

Why does this matter?

You might wonder why we don't just use int variables. Using enums makes your code readable while keeping the efficiency of integers. When you see if (signal == RED), it is much easier to understand than if (signal == 2).

Because these values are sequential, they are also very helpful for logic. For instance, if you have an enum for MONDAY through SUNDAY, MONDAY will be 0 and SUNDAY will be 6. This makes it easy to perform math, like checking if a day is "greater than" Friday to determine if it's the weekend.

Key takeaway

C enumerations start counting at 0 and increase by 1 for each name in the list.