Avoid the use of magic numbers in code when possible. Magic numbers are constant values that represent either an arbitrary value (such as a determined appropriate buffer size, ) or a malleable concept (such as the age a person is considered an adult, which could change between geopolitical boundaries). Rather, use appropriately named symbolic constants to clarify the intent of the code. In addition, if a specific value needs to be changed, reassigning a symbolic constant once is more efficient and less error prone then than replacing every instance of the value to be changed.
Non-Compliant Code Example
The meaning of the numeric literal 18 is not clear in this example.
...
The compliant solution replaces 18 with the symbolic constant ADULT_AGE
to clarify the meaning of the code.
When declaring immutable symbolic values, such as {{ Wiki Markup ADULT_AGE
}} , it is best to declare them as a constant in accordance with \[[DCL00-A. Declare immutable values using enum or const]\].
Code Block | ||
---|---|---|
| ||
enum { ADULT_AGE=18 }; /* ... */ if (age >= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
Exceptions
DCL06-EX1: While replacing numeric constants with a symbolic constant is often a good practice, it can be taken too far. Exceptions can be made for constants that are themselves the abstraction you want to represent, as in this compliant solution.
...
When implementing recommendations, it is always necessary to use sound judgment.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Henricson 1992|AA. C References#Henricson 1992]\] Chapter 10, "[Constants|http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap10.html]" \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7, "Declarations" |
...