...
Non-Compliant Code Example
The meaning of the numeric integer literal 18 is not clear in this example.
...
The compliant solution replaces the integer literal 18 with the symbolic constant ADULT_AGE
to clarify the meaning of the code.When declaring immutable symbolic values, such as ADULT_AGE
, it is best to declare them as a constant in accordance with DCL00-A. Const-qualify immutable objects.
Code Block | ||
---|---|---|
| ||
enum { ADULT_AGE=18 }; /* ... */ if (age >= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
Non-Compliant Code Example
Magic numbers Integer literals are frequently used when referring to array dimensions, as shown in this non-compliant coding example.
Code Block | ||
---|---|---|
| ||
char buffer[256]; /* ... */ fgets(buffer, 256, stdin); |
This use of magic numbers integer literals can easily result in buffer overflows, if for example, the buffer size is reduced but the magic number integer literal used in the call to fgets()
is not.
...
In this compliant solution the magic number integer literal is replaced with an enumeration constant (see DCL00-A. Const-qualify immutable objects).
Code Block | ||
---|---|---|
| ||
enum { BUFFER_SIZE=256 }; char buffer[BUFFER_SIZE]; /* ... */ fgets(buffer, BUFFER_SIZE, stdin); |
Enumeration constants can safely be used anywhere a constant expression is required.
Compliant Solution (sizeof
)
...