Baum mit Augen
Baum mit Augen

Reputation: 50053

Numeric constants in C++

  1. Are numeric constant makros like M_PI known from the C-library math.h part of the C++ standard?
    I cannot find them in my reference.

  2. What is the best way to define custom constants?
    Is a constants.hpp with static constexpr int foo = 7; with a special namespace a good solution?

  3. If the makros from question 1 do exist, should I prefer them for readability or define my own constants (like in 2 or in a better way) for type safety?

Upvotes: 1

Views: 1854

Answers (3)

benf
benf

Reputation: 1005

You could use boost -

#include <boost/math/constants/constants.hpp>

using namespace  boost::math::constants;

double circumference(double radius)
{
    return radius * 2 * pi<double>();
}

see the documentation

Upvotes: 3

csnate
csnate

Reputation: 1641

  1. M_PI is not standard.

  2. I think this is more of a preference. I've seen the following methods:

    #define PI 3.1415
    const double PI = 3.1415;
    const double kPi = 3.1415;
    
  3. Again, I think its a preference or it could depend on what you are actually doing. Also try this:

    #define _USE_MATH_DEFINES
    #include <math.h>
    

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Neither the C Standard nor the C++ Standard defines constant M_PI.

There is no sense to use keyword static in a constant definition because by default constants have internal linkage.

Before defining a constant you should look through the POSIX standard.

Upvotes: 2

Related Questions