ideasman42
ideasman42

Reputation: 48028

Advantages in using an enum to define a single value? (C)

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

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215221

Enumeration constants have several advantages:

  • They're scoped and don't expand in contexts where they shouldn't (as pointed out by mafso).
  • Most debuggers are aware of them and can use them in expressions written in the debugger.

Macros have several different advantages:

  • They can be use in preprocessor conditionals (#if BITS_PER_WORD == 32 won't work if BITS_PER_WORD is an enumeration constant).
  • They can have arbitrary types (also covered in mafso's answer).
  • They can be removed (#undef) when no longer needed.

Upvotes: 9

mafso
mafso

Reputation: 5543

An advantage is that enums 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

Related Questions