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. Appropriately named symbolic constants make code more readable rather than checks against a specific number. If clarify the intent of the programmer. In addition, if a specific number needs to be changed reassigning a symbolic value is much easier than replacing a specific number in the code because each case has to be checked specifically.

Non Compliant Code Example

Code Block
bgColor#ffcccc
if (age >= 18) {
  takevote(personID);
}
...
if (age <= 18) {
  checkSchoolEnrollment(personID);
}

Compliant Solution

Code Block
bgColor#ccccff
enum { ADULT_AGE=18 };
...
if (age >= ADULT_AGE) {
  takevote(personID);
}
...
if (age <= ADULT_AGE) {
  checkSchoolEnrollment(personID);
}

...

DCL00-A. Declare immutable values using const or enum 

Risk Assessment

Mistakes regarding numeric values can cause unintended consequences if changes are not made uniformly

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP00-A

1 (low)

1(unlikely)

2 (medium)

P2

L3

References

Source: http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap10.html