CXX.USE.MAGIC_NUMBER
Use of magic number
Direct use of a numeric literal (excluding integer values 0 and 1). In many cases, 0 and 1 are not magic numbers but are part of the fundamental logic of the code (for example, 0 often represents a NULL pointer). In such cases, 0 and 1 may be used.
Vulnerability and risk
The use of a magic number tends to increase code maintenance efforts, and if the same constant is also used elsewhere, and one or more instances are not kept updated, then unexpected behavior may result.
Mitigation and prevention
Replace a magic number with a constant or macro definition.
Vulnerable code example
#define MACRO 23
enum e { start = 4, end };
const int i = 34;
int j = 10; // Violation
char c = 'c';
char* s = "string";
bool b = true;
float f = 1.0; // Violation
int func (int a)
{
a = MACRO;
a = e.start;
a = i;
a = 0;
a = 1;
a = 29; // Violation
return a;
}
In the above example, the declaration of variables j and f, and the assignment of parameter a to 29 are all violations of this rule. Strings, characters, and the integer values zero and one are all exceptions to this rule.