Versions Compared

Key

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

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 in a different country) in code where it is possiblefrom 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.

...

Code Block
bgColor#ccccff
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.

Code Block
bgColor#ccccff

x = (-b + sqrt(b*b - 4*a*c)) / (2*a);

Replacing numeric constants with symbolic constants in this example does nothing to improve the readability of the code, and may in fact make the code more difficult to read:

Code Block

enum { TWO = 2 };     /* a scalar */
enum { FOUR = 4 };    /* a scalar */
enum { SQUARE = 2 };  /* an exponent */
x = (-b + sqrt(pow(b,SQUARE) - FOUR*a*c))/ (TWO * a);

When implementing recommendations it is always necessary to use sound judgment.

Risk Assessment

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

...