Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 947
somerandomdude Avatar asked May 13 '17 08:05

somerandomdude


People also ask

What is symbolic constant?

A symbolic constant can be defined by using it as a label or by using it as a . set statement. A symbol can be used as a constant by giving the symbol a value. The value can then be referred to by the symbol name, instead of by using the value itself.

What are magic constants in programming?

The term magic number or magic constant refers to the anti-pattern of using numbers directly in source code. This has been referred to as breaking one of the oldest rules of programming, dating back to the COBOL, FORTRAN and PL/1 manuals of the 1960s.

What are symbolic constants examples?

Symbolic constants are nothing more than a label or name that is used to represent a fixed value that never changes throughout a program. For example, one might define PI as a constant to represent the value 3.14159.

What is magic constant in C?

A magic constant would be a numeric value that you just type into some code with no explanation about why it is there.


1 Answers

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.

like image 113
paxdiablo Avatar answered Oct 30 '22 14:10

paxdiablo