Synopsis: | Avoid magic numbers. |
Language: | C |
Severity Level: | 8 |
Category: | Statement and Blocks |
Description: |
Justification Do not use hard-coded numbers. It is better practice to use a macro constant or a typed constant (e.g. "const float"); these can be defined in an appropriate location where they can be easily reviewed and maintained. Furthermore, typed constants have the benefit of allowing the compiler to check their type. Example 1 #define CCBB_SPEED_LIMIT 1.50137 const int OTHER_LIMIT = 3.8014; void CCBB_func(double d); void CCBB_fn(void) { CCBB_func(1.50137); /* WRONG: hard-coded number used */ CCBB_func(CCBB_SPEED_LIMIT); /* RIGHT */ CCBB_func(OTHER_LIMIT); /* RIGHT */ } Example 2 /* Root finding second order equation */ r0 = (-b + sqrt(b * b - 4.0 * a * c) ) / (2.0 * a); /* RIGHT: this will not change */ Example 3 /* Check if FOUP is full */ i = 0; /* RIGHT: indexing always starts at 0 */ full = TRUE; while (full && (i < 25)) /* WRONG: usage of magic number 25 */ { if (my_FOUP[i] == has_no_wafer) { full = FALSE; } i++; } |