somerandomdude
somerandomdude

Reputation: 337

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

In A Tour of C++ by Bjarne Stroustrup, some advice is listed at the end of each chapter. At the end of the first chapter one of them reads:

Avoid ‘‘magic constants;’’ use symbolic constants;

What are magic and symbolic constants?

Upvotes: 14

Views: 4601

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Magic:

int DeepThought() { return 42; }

Symbolic:

const int TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything = 42;
int DeepThought() { return TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything; }

Upvotes: 4

Scott Thompson
Scott Thompson

Reputation: 23701

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.

Upvotes: 7

paxdiablo
paxdiablo

Reputation: 882226

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.

Upvotes: 23

Related Questions