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?
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.
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.
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.
A magic constant would be a numeric value that you just type into some code with no explanation about why it is there.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With