c++ – Which is the better alternative: defines, enums or variables?


Recently, in a project where I have to declare many constants, this question came to me. Which is better define's , enum's or constant variables?

At first I think that using enum is the best alternative because it doesn't pollute the code and works better with the IDE's autocompletor, but what would be the pros and cons of each approach?

Example of the options I have:

enum Pin
    PIN_00 = 0x10,
    PIN_01 = 0x11,
    PIN_02 = 0x12,
    // ... muitos outros 


#define PIN_00 0x10
#define PIN_01 0x11
#define PIN_02 0x12
// ... outros defines


namespace Pin
     const int PIN_00 = 0x10;
     const int PIN_01 = 0x11;
     const int PIN_02 = 0x12;
     // ... Outros declarações


If all the constants are related and you want to give them cohesion in the form of a type, enum is the best choice, as they don't allow you to mistakenly assign them the wrong value.

Pin pin1 = PIN_00; //Ok
Pin pin2 = 0x10;   //Não compila

Now if the purpose is just to name a magic number , there is controversy. Personally I prefer const to #define , because const variables are handled by the compiler itself. You have an identifier, with a well-defined type and value. define is handled by the preprocessor, which can generate unexpected results in some cases. For example:

const int CONST = 2 + 5;
#define DEFINE 2 + 5

int x = 3 * CONST;  //Resultado = 3 * (2 + 5)
int y = 3 * DEFINE; //Resultado = 3 * 2 + 5 !!!

Another problem is that the type of define is only defined by the literal, which can also cause problems:

#define FATOR 1.5

double val = FATOR / 2;

If someone ever changes the value of FATOR to 1 (instead of 1.0 ) that division becomes an integer division, the result of which is 0 , instead of the expected 0.5 . This problem does not happen if FATOR is const double .

Scroll to Top