Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 930
ideasman42 Avatar asked Jul 29 '14 14:07

ideasman42


1 Answers

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.
like image 74
R.. GitHub STOP HELPING ICE Avatar answered Sep 18 '22 12:09

R.. GitHub STOP HELPING ICE