In this article we are going to compare Enum, Macros and Static const variables.

First disadvantage of macros, they may not be seen by the compiler when you try to debug, For example:

The VOLTAGE_FDBK_OFFSET may not be in the symbol table. When you are debugging you will find the “3# but you might not be able to know which is the meaning of that “3”. If that macro was defined in a header that you did not write, then the tracking down to know the meaning of “3” will be more exhausting.

To prevent this, there are two options; const variable and enum definition.

An enum definition will work the best when you have related definitions:

If the macro has no relation with others; you might want to use a static const variable instead:

Both, enum and static const, have a symbol in the symbol table. Therefore you will find them in the debug tool easier.

As a side note, in C90, the static const variable cannot be used as a index in global and static function scope arrays. This is because the size of the arrays need to be constant expression (literal constants or sizeof expressions), and static const are not constant expressions. This is a C90 language limitation, In C99, there are runtime- boundary arrays, and in C++, static const and constexpr are indeed constant expressions.

In array size definition, you can use enums and macros instead.

Enums should be used as a group of associate integer constants. If you have a sequence of #define that share the same context, prefer the use of enums.

Of course, if you have a solitary definition, it is better to define it as macro:

Enums are also better than macros to define states in state machine strategies:

Macros can be defined in the smallest type that the compiler allows. Enums implementation is defined to be int by the standard C, but compiler’s optimizations have the option to store enums in the smallest space possible. Enums, by themselves, do not use data space, they are compile-time symbols, so they will end up in code space!

Enum and macros can be used as switch-cases, while static const variables cannot. In this case, prefer enums as we can check that there is no missing case.

To remember:

1. Use only macros when the definition has no relation with other definitions AND the consumption of memory space is a real problem.
2. Use static const instead of macros when the definition is not used as an array size and the comsumption of memory space is not a problem.
3. Use enum in all other cases: i.e switch cases, state machine state, array indexing…

Leave a Reply

Your email address will not be published.