Magic number are the constants ,array sizes ,character positions ,conversion factors and other literal numeric values that appears in programs.
Give names to magic number.
By giving names to the principal numbers in the calculation, we can make the code easier to follow.
Define numbers as constants, not macros.
In C and C++,integer constants can be defined with enum statement.
In C++:
const int Maxrow=24,Maxcol=80;
In Java:
static final int Maxrow=24,Maxcol=80;
Use character constants,not integers.
We prefer to use different explicit constants, reserving 0 for a literal integer zero.
Don't write
? str= 0;
? name[i]= 0;
? x= 0;
but rather:
str = NULL;
name[i]= '\0';
x= 0.0;
Use the language to calculate the size of an object
In C/C++, for an array(not a pointer) whose declaration is visible ,this macro computes the number of elements in the array:
#define NELEMS(array) (sizeof(array) / sizeof(array[0] ))
double dbuf[100];
for (i=0; i< NELEMS(dbuf); i++)
...
This compute the size of array from its declaration which a function cannot.