Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use enum when #define is just as efficient? [duplicate]

Tags:

c

enums

So an enum works like this:

enum {
  false,
  true
}

which is equivalent to

int false = 0
int true = 1

Why wouldn't I substitute enum with #define?

#define FALSE 0
#define TRUE 1

To me, it seems like they are interchangeable. I'm aware that #define is able to handle arguments, hence operates in an entirely different way than enum. What exactly are the main uses of enum when we have #define in this case?

If I were to guess, as the #define is a preprocessor feature, enum would have some runtime advantages. How far off am I?

Thanks in advance.

like image 660
userenum Avatar asked Mar 09 '11 08:03

userenum


People also ask

When should enum be used?

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Why do we need enum?

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Why enums are better than constants?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

What is the benefit of using enum in Java?

Advantages of enumsType safety: Enums provide compile-time type safety and prevent from comparing constants in different enums.


2 Answers

The advantages of enum show up when you have a long list of things you want to map into numbers, and you want to be able to insert something in the middle of that list. For example, you have:

pears 0
apples 1
oranges 2
grapes 3
peaches 4
apricots 5

Now you want to put tangerines after oranges. With #defines, you'd have to redefine the numbers of grapes, peaches, and apricots. Using enum, it would happen automatically. Yes, this is a contrived example, but hopefully it gives you the idea.

like image 89
jcomeau_ictx Avatar answered Oct 14 '22 04:10

jcomeau_ictx


I find it useful for debugging in an environment such as gdb since enum values are handled at compile time (where #define is a preprocessor macro) and thus available for introspection.

like image 25
mduvall Avatar answered Oct 14 '22 03:10

mduvall