What are “symbolic constants” and “magic constants”?

In A Tour of C ++ by Bjarne Stroustrup, some tips are 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 the magic and symbolic constants?

+7
source share
3 answers
somethingElse = something * 1440;           // a magic constant
somethingElse = something * TWIPS_PER_INCH; // a symbolic one

Firstly, this is an example of a magic constant; it does not transmit any information other than its value.

The latter is much more useful because the intention is clear.

Using a character constant also helps a lot if you have several things with the same value:

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

, , , 1440 . 1440 , ​​, .

+12

A magic constant , . . :

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

" " 3.14159 , .

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

, , , ... "" .

+7

Magic:

int DeepThought() { return 42; }

:

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

Source: https://habr.com/ru/post/1677062/


All Articles