You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

Avoid the use of numerical values or "magic numbers" in code when possible. Appropriately named symbolic constants clarify the intent of the programmer. In addition, if a specific number needs to be changed reassigning a symbolic value is more efficient and less error prone than replacing every instance of specific number in the code.

Non Compliant Code Example

if (age >= 18) {
   /* Take action */
}
...
if (age < 18) {
  /* Take a different action */
}

Compliant Solution

enum { ADULT_AGE=18 };
...
if (age >= ADULT_AGE) {
   /* Take action */
}
...
if (age < ADULT_AGE) {
  /* Take a different action */
}

In the compliant code it is easy to check if the user is an adult and process accordingly. If the definition of adult changes during iterations of the codebase it is much simpler to replace the value for ADULT_AGE in one place then search for instance of 18 and see if they're appropriate for change.

When declaring immutable symbolic values such as ADULT_AGE it is best to use const or enum as explained in

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

  • No labels