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

c++, constants

Solution

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 `1440`s scattered throughout the code, you have to change it in multiple places and figure out which are the twips and which are the sectors.

Problem

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?

Original source

Related problems