Using C++, say I need the value of pi (3.14) for two functions. In regards to the performance of my program, which is better, declaring pi as a global variable and use it in both my functions or declaring it twice inside the functions as a limited scope variable that will die when each function goes out of memory? Obviously the difference is marginal for just this example, but if you multiply this case by x100 for a bigger program, maybe it will actually matter, that’s why I am asking.
The answer is neither. Pi is a constant not a variable, and is defined in <numbers>
in C++20, or commonly by M_PI
in <math.h>
/ <cmath>
(requires _USE_MATH_DEFINES
in VC++, but not gnu or clang)
Certainly you should never have multiple independent instances of the same constant value; but it is less a performance issue and more a maintenance and consistency issue. You would have multiple places in which to get it correct, and in the case if floating point values, may cause errors and discrepancies simply by using a differing number of significant digits for different definitions for irrational numbers such as pi.
For the more general question of how any constant might be defined, then I would suggest that <numbers>
acts as an exemplar as to how it should be done. The std::numbers
constants are declared as constexpr
in a namespace.
But it remains the case that neither approach will impact performance, but clearly multiple instances of the same constexpr
remains ill-advised for the reasons already described not related to performance.
In some cases where the constant is part of a number of closely related classes and is itself very specialised (i.e. not general such as pi), you could make the constant a static constexpr
member of a base class from which all other classes that use the constant are derived.
Either way the DRY principle should be adhered to, which precludes multiple declarations of any constant.