Use symbolic constants instead of magic numerical constants – EasyHack

There are many situations that you need to use numerical constants in your code. If you use numerical literal values directly instead of symbolic constants, it can cause problems.

For example, consider this piece of code that calculate area of a circle:

double area = 3.14 * r * r;

This is not OK, because:

1. The value of π is not 3.14 nor 3.141592. π is an irrational number, and the suitable value depends on the number of decimal places that you can/want to use among unlimited decimals of π.

2. Suppose that you want to change the numerical literal to increase the number of decimals that you use. You should search for 3.14, and check one by one to see if it is actually π, or it is another 3.14 unrelated to the well-known mathematical constant.

C++ logo

C++ is the main programming language used in the LibreOffice development

Using symbolic constants

A better code can be:

double area = M_PI * r * r;

and with more long and meaningful name for variables:

double circle_area = M_PI * radius * radius;

Because of the above mentioned problems, it is better to use some numerical constant instead.

ES.45: Avoid “magic constants”; use symbolic constants

If it is well-known (like π), you should use the appropriate symbolic constant like M_PI. If not, you should define a new constant with proper name and type with ‘contsexpr’.

One solution to find such magic constants is to start from a list of some well known mathematical constants:

Then, store some of them in a text file, let’s say ‘constants.txt’, then search for all these values inside C++ files:

git grep -Ff constants.txt *.cxx *.hxx

Many of these symbolic constants like M_PI already exist in C++ standard library or some place in the LibreOffice code, and you can use them easily.

You should examine the ‘grep’ results carefully, because not every 3.14 refers to PI.

Final Notes

Besides fixing the bugs, there are many places to work on improving the code, and some of these are listed as EasyHacks. The specific improvement that is discussed in this blog post is filed as tdf#145759.

If you want to work on this improvement about using symbolic constants, but you need to know how to get started with LibreOffice development, I suggest you to see our video tutorial:

Getting Started (Video Tutorial)