...
Code Block | ||
---|---|---|
| ||
enum { ADULT_AGE=18 }; /* ... */ if (age >= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ |
Non-Compliant Code Example
Magic numbers 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 can easily result in buffer overflows, if for example, the buffer size is reduced but the magic number used in the call to fgets()
is not.
Compliant Solution (enum)
In this compliant solution the magic number is replaced with an enumeration constant (see DCL00-A. Declare immutable values using enum or const).
Code Block | ||
---|---|---|
| ||
enum { BUFFER_SIZE=256 };
char buffer[BUFFER_SIZE];
/* ... */
fgets(buffer, BUFFER_SIZE, stdin);
|
Compliant Solution (((sizeof}})
A sizeof
expression can work just as well as an enumeration constant (see EXP09-A. Use sizeof to determine the size of a type or variable).
Code Block | ||
---|---|---|
| ||
char buffer[256];
/* ... */
fgets(buffer, sizeof(buffer), stdin);
|
Using the sizeof
expression reduces the total number of names declared in the program, which is almost always a good thing to do.
Exceptions
DCL06-EX1: While replacing numeric constants with a symbolic constant is often a good practice, it can be taken too far. Exceptions can be made for constants that are themselves the abstraction you want to represent, as in this compliant solution.
...