Why are there two ways to "declare" constants in CPP?
Which is better, or should I write, which of them should I use when?
#define MYCON 100
const int MYCON=100
Short rule: For conditional compilation (like different code fragments for DEBUG and RELEASE) use #define. For all other cases use const construction.
Using #define produces a preprocessor symbol: it has no existence at all after preprocessing has occurred and is equivalent to having typed "100" into the file.
Features of preprocessor symbols:
#ifdeftype* is expected)Using const type declares a c++ variable.
It is widely considered better to use const for "in program" constants and #define only for conditional compilation (which represents a change from the (very!) old days when you could not always rely on c compiler to handle const intelligently and using #define was preferred). If nothing else this gives you better control of the symbol's scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With