Immutable (constant values) should be declared as const-qualified objects (unmodifiable lvalues), enumerations values, or as a last resort, using #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-qualified objects cannot be used where compile-time integer constants are required, namely:
- size of a bit-field member of a structure
- size of an array
- value of an enumeration constant
- value of a
case
constant.
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.
Non-Compliant Code Example 1
In this example, PI
is defined using a macro. In the code, the value is introduced by textual subsitution.
#define PI 3.14159 ... float degrees; float radians; ... radians = degrees*PI/180;
Compliant Solution 1
In this compliant solution, the constant is defined as a const
variable.
float const pi = 3.14159; ... float degrees; float radians; ... radians = degrees*pi/180;
Non-Compliant Code Example 2
Delcaring immutable integer values as const-qualified objects still allows the programmer to take the address of the object. Also, the constant cannot be used in locations where an an integer constant is required, such as the size of an array.
int const max = 15; int const *p; int a[max]; /* invalid declaration */ p = &max; /* legal to take the address of a const-qualified object */
Most C compilers will also allocate memory for the const-qualified object.
Compliant Solution 2
This compliant solution uses an enum
rather than const-qualified object or a macro definition.
enum { max = 15 }; int a[max]; /* OK */ p = &max; /* error: '&' on constant */
Risk Assessment
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DCL00-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
References
- ISO/IEC 9899-1999 Sections 6.3.2.1, "Lvalues, arrays, and function designators"; 6.7.2.2, "Enumeration specifiers"; 6.10.3, "Macro replacement"