In embedded programming, for example, #define GLOBAL_CONSTANT 42 is preferred to const int GLOBAL_CONSTANT = 42; for the following reasons:
- it does not need place in RAM (which is usually very limited in microcontrollers, and µC applications usually need a large number of global constants)
constneeds not only a storage place in the flash, but the compiler generates extra code at the start of the program to copy it.
Against all these advantages of using #define, what are the major advantages of using const?
In a non-µC environment memory is usually not such a big issue, and const is useful because it can be used locally, but what about global constants? Or is the answer just “we should never ever ever use global constants”?
Edit:
The examples might have caused some misunderstanding, so I have to state that they are in C. If the C compiler generated the exact same code for the two, I think that would be an error, not an optimization.
I just extended the question to C++ without thinking much about it, in the hopes of getting new insights, but it was clear to me, that in an object-oriented environment there is very little space for global constants, regardless whether they are macros or consts.
The answer to your question varies for C and C++.
In C,
const int GLOBAL_CONSTANTis not a constant in C, So the primary way to define a true constant in C is by using#define.In C++, One of the major advantage of using
constover#defineis that#definesdon’t respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.Apart from that there are other subtle advantages like:
Avoiding Weird magical numbers during compilation errors:
If you are using
#definethose are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.Ease of Debugging:
Also for same reasons mentioned in #2, while debugging
#definewould provide no help really.