Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define or enum? [duplicate]

Tags:

c

Possible Duplicate:
Why use enum when #define is just as efficient?

When programming in C, is it better practice to use #define statements or enums for states in a state machine?

like image 372
SSS Avatar asked Jun 28 '10 17:06

SSS


2 Answers

Technically it doesn't matter. The compiler will most likely even create identical machine code for either case, but an enumeration has three advantages:

  1. Using the right compiler+debugger combination, the debugger will print enumeration variables by their enumeration name and not by their number. So "StateBlahBlup" reads much nicer than "41", doesn't it?

  2. You don't have explicitly give every state a number, the compiler does the numbering for you if you let it. Let's assume you have already 20 states and you want to add a new state in the middle, in case of defines, you have to do all renumbering on your own. In case of enumeration, you can just add the state and the compiler will renumber all states below this new state for you.

  3. You can tell the compiler to warn you if a switch statement does not handle all the possible enum values, e.g. because you forgot to handle some values or because the enum was extended but you forgot to also update the switch statements handling enum values (it will not warn if there's a default case though, as all values not handled explicitly end up in the default case).

like image 72
Mecki Avatar answered Oct 19 '22 23:10

Mecki


Since the states are related elements I think is better to have an enum defining them.

like image 37
Daniel Băluţă Avatar answered Oct 20 '22 00:10

Daniel Băluţă