Search code examples
cenumsintegerintconstants

Difference between using enum and int variables in C


What is the difference between

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum week day = Wed; 

and

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int day = Wed;

in C?

I couldn't find what is the benefit of using variables of type enum over using a regular int.


Solution

  • The benefit is that using an enum make your intentions clearer, both to people reading your code and to the compiler. For example, any half-way decent compiler will warn you if you use an enum with incomplete switch cases:

    switch (day) {
        case Mon: printf("Monday\n"); break;
        case Tue: printf("Tuesday\n"); break;
    }
    

    Here GCC (with -Wall) emits:

    warning: enumeration value 'Wed' not handled in switch [-Wswitch]

    7 |     switch (day) {
      |     ^~~~~~
    

    If the type of day was int, you wouldn’t get this very helpful warning.