Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 673
Amirreza A. Avatar asked Dec 18 '22 12:12

Amirreza A.


1 Answers

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.

like image 198
Konrad Rudolph Avatar answered Dec 31 '22 02:12

Konrad Rudolph