Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider (sch jbop) (X_X)@==(Q_Q)@

...

Code Block
bgColor#ffcccc
/* // ... */
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
bgColor#ccccff
enum { ADULT_AGE=18 };
/* // ... */
if (age >= ADULT_AGE) {
   /* Take action */
}
else {
  /* Take a different action */
}
/* // ... */

Exceptions

While replacing numeric constants with a symbolic constant is often a good practice, it can be taken too far. Exceptions can be made for constants that are themselves the abstraction you want to represent, as in this compliant solution.

...

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);

...

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"