Avoid the use of magic numbers in code when possible. Magic numbers are constant values that represent 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 from one location to another. Rather, use appropriately named symbolic constants 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 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.
Code Block | ||
---|---|---|
| ||
/* ... */ if (age >= 18) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
Compliant Solution
The compliant solution replaces 18 with the symbolic constant ADULT_AGE
to clarify the meaning of the code.
...
Code Block | ||
---|---|---|
| ||
enum { ADULT_AGE=18 }; /* ... */ if (age >= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
Compliant Solution
While replacing numeric constants with a symbolic constant is often a good practice, it can be taken too far. In this compliant solution, for example, the quadratic theorem is provably correct" with hardcoded constants that will never be changed.
...
When implementing recommendations it is always necessary to use sound judgment.
Risk Assessment
Using numeric literals makes code more difficult to read and understand.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
[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" |