10. Constants
- Rule 36
- Constants are to be defined using
const or enum ; never using #define .
- Rule 37
- Avoid the use of numeric values in
code; use symbolic values instead.
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.
- Exception to Rule 36
- No exceptions.
- Exception to Rule 37
- Certain numerical values have a well
established and clear meaning in a program. For example, '1' and '0'
are often used to represent 'true' and 'false' respectively. These may
be used directly in code without being considered to be "Magic".
Example 42: Different ways of declaring constants.
// 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
Example 43: Declaration of const defined in another file.
extern const char constantCharacter;
extern const String fileName;
|