I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it somehow related to compiler level or not?
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
What is the benefit of using an enum rather than a #define constant? The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.
Enums are strongly-typed constants that make the code more readable and less prone to errors. Enums are known as named constants. If we have some constants related to each other then we can use an enum to group all the constants.
In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, enum
defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter.
Compare
#define UNKNOWN 0 #define SUNDAY 1 #define MONDAY 2 #define TUESDAY 3 ... #define SATURDAY 7
to
typedef enum { UNKNOWN, SUNDAY, MONDAY, TUESDAY, ... SATURDAY, } Weekday;
It is much easier to read code like this
void calendar_set_weekday(Weekday wd);
than this
void calendar_set_weekday(int wd);
because you know which constants it is OK to pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With