const
or enum
; never using #define
.
The preprocessor performs a textual substitution for macros in the
source code which is then compiled. This has a number of negative
consequences. For example, if a constant has been defined using
#define
, the name of the constant is not recognized in
many debuggers. If the constant is represented by an expression, this
expression may be evaluated differently for different instantiations,
depending on the scope of the name. In addition, macros are, at times,
incorrectly written.
Numerical values in code ("Magic Numbers") should be viewed with
suspicion. They can be the cause of difficult problems if and when
it becomes necessary to change a value. A large amount of code can
be dependent on such a value never changing, the value can be used at
a number of places in the code (it may be difficult to locate all of
them), and values as such are rather anonymous (it may be that every
`2
' in the code should not be changed to a `3
').
From the point of view of portability, absolute values may be the cause of more subtle problems. The type of a numeric value is dependent on the implementation. Normally, the type of a numeric value is defined as the smallest type which can contain the value.
// Constants using macros #define BUFSIZE 7 // No type checking // Constants using const const int bufSize = 7; // Type checking takes place // Constants using enums enum SIZE { BufSize = 7 }; // Type checking takes place
const
defined in another file.extern const char constantCharacter; extern const String fileName;