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?
Technically it doesn't matter. The compiler will most likely even create identical machine code for either case, but an enumeration has three advantages:
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?
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.
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).
Since the states are related elements I think is better to have an enum defining them.
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