Reputation: 48028
Recently, in this question I saw an enum used to define a single value. eg:
enum { BITS_PER_WORD = 32 };
Instead of:
#define BITS_PER_WORD 32
Assuming more members won't be added later, what - if any, are the advantages of doing this? (or is this more a a question of personal taste )
Said differently, if I have existing code using one-off int defines, is there any good reason to change these around for one-off enums shown above?
Out of curiosity I compared GCC's optimized assembler output for some non-trivial code and the result was unchanged betweem enums/defines.
Upvotes: 6
Views: 1096
Reputation: 215221
Enumeration constants have several advantages:
Macros have several different advantages:
#if BITS_PER_WORD == 32
won't work if BITS_PER_WORD
is an enumeration constant).#undef
) when no longer needed.Upvotes: 9
Reputation: 5543
An advantage is that enum
s are scoped and you can define the enum
inside a block. A macro would also expand for e.g.:
foo.BITS_PER_WORD;
or even
void foo(int BITS_PER_WORD) { /* ... */ }
An advantage of a macro is, that you can define it to non-int
values.
Upvotes: 5