3
Jan/08
1

Do not use magic numbers!

Well let’s take an example :

int i;

for (i = 0; i < 128; i++)
{
switch(ship[i].type)
{
case 0 : ship[i].speed = 100.0f; break;
//…
}
}

Got the point? Those numbers there doesn’t tell a thing about them, that’s why it is good practise to get rid of the numbers and replace them with something more understandable. Check the modified version :

enum ShipType
{
SHIP_TYPE_CARRIER=0,
//…
SHIP_TYPE_MAX
};

#define SHIP_SPEED_SLOW 100.0f
#define NUM_SHIPS 128

int i

for (i = 0; i < NUM_SHIPS; i++)
{
switch(ship[i].type)
{
case SHIP_TYPE_CARRIER : ship[i].speed = SHIP_SPEED_SLOW; break;
//…
default : assert(ship[i].type < SHIP_TYPE_MAX); break;
}
}

That’s better right? :)

It is very important to keep your code readable!

By the way if anybody knows a good way to display code, please let me know as this sucks. :)

Post to Twitter

Filed under: Tips&Tricks
Comments (1) Trackbacks (0)
  1. Kitty
    6:34 pm on October 27th, 2008

    Great work.

Leave a comment

No trackbacks yet.