Advantages of using an enumeration to define a single value? (WITH)

Recently, in this question , I saw an enumeration used to define a single value. eg:

enum { BITS_PER_WORD = 32 }; 

Instead:

 #define BITS_PER_WORD 32 

Assuming no more participants will be added later, what - if any - are the benefits of this? (or is it more a matter of personal taste)

In other words, if I have existing code using one-time int values, are there any good reasons to change them for the one-time enumerations shown above?

Out of curiosity, I compared the GCC-optimized assembler output for some non-trivial code, and the result did not change between the two enumerations / defines.

+6
source share
2 answers

Enumeration constants have several advantages:

  • They are limited and do not expand in contexts where they should not (as indicated by mafso).
  • Most debuggers know about them and can use them in expressions written in the debugger.

Macros have several different advantages:

  • They can be used in preprocessor conditions ( #if BITS_PER_WORD == 32 will not work if BITS_PER_WORD is an enumeration constant).
  • They can be of arbitrary types (also covered in mafso's answer).
  • They can be removed ( #undef ) when they are no longer needed.
+9
source

The advantage is that enum limited, and you can define enum inside a block. The macro will also expand, for example:

 foo.BITS_PER_WORD; 

or even

 void foo(int BITS_PER_WORD) { /* ... */ } 

The advantage of a macro is that you can define it for non int values.

+5
source

Source: https://habr.com/ru/post/973045/


All Articles