What are "symbolic constants" and "magic constants"?

A magic constant would be a numeric value that you just type into some code with no explanation about why it is there. Coming up with a good example is challenging. But let's try this:

float areaOfCircle(float radius) {
    return radius * radius * 3.14159
}

Here I've used a "magic constant" of 3.14159 without any explanation of where it comes from. It would be better style to say

const float pi = 3.14159
float areaOfCircle(float radius) {
    return radius * radius * pi;
}

Here I've given the person reading the code some idea about where the constant came from and why it was used... it didn't seem to "magically" appear out of nowhere.


somethingElse = something * 1440;           // a magic constant
somethingElse = something * TWIPS_PER_INCH; // a symbolic one

The first is an example of the magic constant, it conveys no other information other than its value.

The latter is far more useful since the intent is clear.

Using symbolic constant also helps a great deal if you have multiple things with the same value:

static const int TWIPS_PER_INCH = 1440;
static const int SECTORS_PER_FLOPPY = 1440; // showing my age here :-)

That way, if one of them changes, you can easily identify which single 1440 in the code has to change. With magic 1440s scattered throughout the code, you have to change it in multiple places and figure out which are the twips and which are the sectors.

Tags:

C++

Constants