...
The following table summarizes some of the differences between const
-qualified objects, enumeration constants, and object-like macro definitions.
Method | Evaluated At | Consumes Memory | Viewable by Debuggers | Type Checking | Compile-Time Constant Expression |
---|---|---|---|---|---|
Enumerations | Compile time | No | Yes | Yes | Yes |
| Runtime | Yes | Yes | Yes | No |
Macros | Preprocessor | No | No | No | Yes |
Noncompliant Code Example
...
Using numeric literals makes code more difficult to read and understand. Buffer overruns are frequently a consequence of a magic number being changed in one place (such as in an array declaration) but not elsewhere (such as in a loop through an array).
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL06-C | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
Compass/ROSE |
Could detect violations of this recommendation merely by searching for the use of "magic numbers" and magic strings in the code itself. That is, any number (except a few canonical numbers: −1, 0, 1, 2) that appears in the code anywhere besides where assigned to a variable is a magic number and should instead be assigned to a | |||||||||
| CC2.DCL06 | Fully implemented | |||||||
LDRA tool suite |
| 201 S | Fully implemented | ||||||
Parasoft C/C++test |
|
|
| CODSTA-26 | Fully implemented | |||||||
Polyspace Bug Finder | R2016a | Size of memory buffer is a numerical value instead of symbolic constant Loop boundary is a numerical value instead of symbolic constant | |||||||
PRQA QA-C |
| 3120 | Partially implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | VOID DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic |
MITRE CWE | CWE-547, Use of hard-coded, security-relevant constants |
Bibliography
[Henricson 1992] | Chapter 10, "Constants" |
[Saks 2001a] |
[Saks 2001b] |
[Saks 2002] |
[Summit 2005] | Question 10.5b |
...
...