Search code examples
c++c

What is the use of enums in C and C++


Enum is list of constant integer values. It can be used instead of defining constant values using #define. But other than that, I haven't found any substantial uses of enums in C and CPP. Can any one please let me know what are the exact uses of enums.

Initially I thought if we create a enum variable and assign a value which is not in the enum values, the compiler will shout. But that is not true. We can assign any value to the enum variable. I can't think of any substantial uses of enum.


Solution

  • Advantages over macros

    • Debuggers can print names for values
    • Your constants will be scoped (if you want, you can put them also in a namespace in C++)
    • The compiler can warn if you forget an enum constant in a switch
    • Values for the constants are automatically assigned, if you don't give explicit values
    • The enum type is always large enough to hold all the constants. When using #define, you have to commit to int or some typedef and ensure that all the constants fit manually