Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Avoid the use of numerical values or "magic numbers" in code when possible. 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
bgColor#ffcccc
if (age >= 18) {
   /* Take action */
}
...
if (age < 18) {
  /* 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
bgColor#ccccff
enum { ADULT_AGE=18 }; 
...
if (age >= ADULT_AGE) {
   /* Take action */
}
...
if (age < ADULT_AGE) {
  /* Take a different action */
}

Risk Assessment

Using numeric literals makes code more difficult to read and understand.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL06-A

1 (low)

1(unlikely)

2 (medium)

P2

L3

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"