[ACCEPTED]-Why use enum when #define is just as efficient?-enums
The advantages of enum
show up when you have 9 a long list of things you want to map into 8 numbers, and you want to be able to insert 7 something in the middle of that list. For 6 example, you have:
pears 0 apples 1 oranges 2 grapes 3 peaches 4 apricots 5
Now you want to put tangerines
after 5 oranges
. With #define
s, you'd have to redefine the numbers 4 of grapes
, peaches
, and apricots
. Using enum, it would happen 3 automatically. Yes, this is a contrived 2 example, but hopefully it gives you the 1 idea.
I find it useful for debugging in an environment 3 such as gdb since enum values are handled 2 at compile time (where #define is a preprocessor 1 macro) and thus available for introspection.
Although your question is tagged as C, there 4 is a big advantage when writing in C++, you 3 can place enum:s
inside classes or namespaces.
This 2 way you could refer to your constants like 1 SpaceshipClass::galaxy
.
enum is an integer constant. so, there would 1 be a type check during compilation process.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.