What is the best alternative: define, enums or variables?

10

Recently, in a project where I have to declare many contributors, I had this doubt. What is the best option define's , enum's or constant variables?

At first I think using enum is the best alternative for not polluting the code and working better with the IDE self-completer, but what the pros and contras

asked by anonymous 06.03.2014 / 15:57

2 answers

11

If all the counters are related and you want to give them cohesion in the form of a type, enum is the best choice because they do not allow you to mistakenly assign them a wrong value.

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

Now if the purpose is just to name a number magical, "there is controversy. I personally prefer% with% of% than% with% because%% of variables are handled by the same compiler. You have an identifier, with a well-defined type and value. The const is treated 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 someday someone changes the value from const to define (instead of define ) that division becomes an integer division, whose result is FATOR , instead of 1 expected. This problem does not happen if 1.0 is 0 .

    
06.03.2014 / 18:10
2

There are several pros and cons of each approach depending on the context, with regard to memory consumption and performance I believe that the enum and the constant variable are the same since the enum is like a more strongly typed variable. Already defines it does not occupy memory since it is evaluated by the preprocessor that replaces the part in which it appears by its definition.

    
06.03.2014 / 17:56