User:Hossein/Blog/const

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 value directly, it can cause problems. For example, consider this piece of code that calculate area of a circle:

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 this is supposed to be π, or it is another 3.14 unrelated to the well-known mathematical constant.

A better code can be:

and with more long and meaningful name for variables:

Because of these problems, it is suggested that it should be replaced by some symbolic constant.


 * C++ Core Guidelines - ES.45: Avoid “magic constants”; use symbolic constants

If it is 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:


 * Wikipedia - List of mathematical constants
 * The GNU C library: predefined mathematical constants
 * Microsoft C runtime library: math constants

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

Many of these symbolic constants like M_PI are already defined 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.


 * Bug 145759 - Use symbolic constants instead of magic numerical constants