If a constant value is given for a given an identifier, do not diminish the modifiability of the code in which it is used by assuming its value in expressions. Just giving the constant a name is not enough to ensure modifiability; you must be careful to always to use the name, and remember that the value could change. This recommendation is related to DCL06-A. Use meaningful symbolic constants to represent literal values in program logic.
Non-Compliant
...
Code Example
This non-compliant coding code example defeats the purpose of defining BUFSIZ
as a constant by assuming its value in the following expression:
Code Block | ||
---|---|---|
| ||
nblocks = nbytes >> 9; /* hard to modify, uses "magic number" */ |
The programmer's assumption underlying this code is that "everyone knows that BUFSIZ
equals 512," and right-shifting nine bits is the same (for positive numbers) as dividing by 512. However, if BUFSIZ
changes to 1024 on some systems, modifications are difficult and error-prone.
...
This compliant solution uses the identifier assigned to the constant value in the expression.
...