Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes a better constant in C, a macro or an enum?

Tags:

c

enums

macros

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?

like image 722
Varun Chhangani Avatar asked Jun 15 '13 16:06

Varun Chhangani


People also ask

Is it better to use enum or constant?

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?

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.

What is the advantage of enum in C?

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.

Should enums be constants?

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.


1 Answers

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.

like image 65
Sergey Kalinichenko Avatar answered Sep 28 '22 04:09

Sergey Kalinichenko