Use Symbolic Constants for Literal Values (RPP14)
Level \(\rightarrow\) Advisory
- Category
- Safety:
\(\checkmark\)
- Cyber:
\(\checkmark\)
- Goal
- Maintainability:
\(\checkmark\)
- Reliability:
\(\checkmark\)
- Portability:
\(\checkmark\)
- Performance:
- Security:
Remediation \(\rightarrow\) Low
Verification Method \(\rightarrow\) GNATcheck rule:
Numeric_Literals
(builtin rule)
Reference
N/A
Description
Extensive use of literals in a program can lead to two problems. First, the meaning of the literal is often obscured or unclear from the context. Second, changing a frequently used literal requires searching the entire program source for that literal and distinguishing the uses that must be modified from those that should remain unmodified.
Avoid these problems by declaring objects with meaningfully named constants, setting their values to the desired literals, and referencing the constants instead of the literals throughout the program. This approach clearly indicates the meaning or intended use of each literal. Furthermore, should the constant require modification, the change is limited to the declaration; searching the code is unnecessary.
Some literals can be replaced with attribute values. For example, when
iterating over an array, it is better to use
Array_Object'First .. Array_Object'Last
than using 1 .. Array_Object'Length
.
Applicable Vulnerability within ISO TR 24772-2
N/A
Applicable Common Weakness Enumeration
Noncompliant Code Example
type Array_T is array (0 .. 31) of Boolean;
function Any_Set (X : Array_T) return Boolean is
(for some Flag in 0 .. 31 => X (Flag));
Compliant Code Example
Number_Of_Bits : constant := 32;
type Array_T is array (0 .. Number_Of_Bits - 1) of Boolean;
function Any_Set (X : Array_T) return Boolean is
(for some Flag in X'Range => X (Flag));
Notes
N/A