It is no secret that using constants in your C++ code can make your code easier to read and maintain, allowing you to eliminate magic numbers, aka raw numerical values floating in your code with no clear meaning or definition. A simple const or constexpr (see here to learn more about the differences) can quickly improve the quality of your code.
Some numbers are easily recognizable from their raw numerical values. Consider 3.14, the widely known constant for pi — a C++ program that calculates nearly any mathematical value involving curves will need to use the value of pi in its code. Prior to C++20, this could be achieved using the following:
constexpr double c_pi = 3.14159;
double calculateCircleArea(const double radius) {
return c_pi * (radius * radius);
}
However, this programmer-defined value for pi may be different than other programs involving this value. Perhaps one programmer uses 3.14
rather than 3.14159
. Prior to C++20, there is no standard way to define the value of pi, along with several other common constants.
Luckily, C++20 has introduced the <numbers>
header that defines many of these mathematical values in the std::numbers
namespace, including pi, e, phi, and more. Now, our code example can be rewritten as the following:
#include <numbers>
double calculateCircleArea(const double radius) {
return std::numbers::pi * (radius * radius);
}
Conclusion
If you are in need of using popular mathematical constants in your C++20 code, consider using the values defined in the <numbers>
header. The full list of supported constants is available here.