Versions Compared

Key

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

Immutable (constant values) should be declared as const-qualified objects (unmodifiable lvalues), enumerations values, or as a last resort, using a #define.

In general, it is preferable to declare immutable values as const-qualified objects rather than as macro definitions. Using a const declared value means that the compiler is able to check the type of the object, the object has scope, and (certain) debugging tools can show the name of the object. Const const-qualified objects cannot be used where compile-time integer constants are required, namely to define the:

...

If any of these are required, then an integer constant (an rvalue) must be used. For integer constants, it is preferable to use an enum instead of a const-qualified object as this eliminates the possibility of taking the address of the integer constant and does not required that storage is allocated for the value.

...

In this example, PI is defined using a macro. In the code, the value is introduced by textual subsitutionsubstitution.

Code Block
bgColor#FFCCCC
#define PI 3.14159
/* ... */
float degrees;
float radians;
/* ... */
radians = degrees*PI/180;

...

Code Block
bgColor#ccccff
float const pi = 3.14159;
/* ... */
float degrees;
float radians;
/* ... */
radians = degrees*pi/180;

...

Most C compilers will also allocate memory for the const-qualified object.

Compliant Solution 2

This compliant solution uses an enum rather than a const-qualified object or a macro definition.

Code Block
bgColor#ccccff
enum { max = 15 };
int a[max]; /* OK */
int const *p;

p = &max; /* error: '&' on constant */

Risk Assessment

Failing to declare immutable values using const or enum can result in a value intended to be constant being changed at runtime.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL00-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Examples of vulnerabilities resulting from the violation of this recommendation can be found on the
CERT website.

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.3.2.1, "Lvalues, arrays, and function designators," Section 6.7.2.2, "Enumeration specifiers," and Section 6.10.3, "Macro replacement"