1

I am using constexpr in my application and I am getting compilation error.

namespace {
   const int kLength = 1;
   const float kPiNumber = 3.14159265;
   constexpr float kCircumferenceArc()
   { return (2*kPiNumber*kLength) / 360; }
}

And the error I am getting is:

read of non-constexpr variable 'kPiNumber' is not allowed in a constant expression { return (2*kPiNumber) / 360; }

Could someone help me on this?

Thanks in advance

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
RuLoViC
  • 825
  • 7
  • 23
  • 1
    `const` integral variables with `constexpr` initializers are automatically made `constexpr`, but floating-point ones aren't. The solution is to make `kPiNumber` constexpr. – HolyBlackCat Jul 21 '18 at 09:06

1 Answers1

2

A constexpr variable must be initialized from values known at compile time. A const variable, like:

const float kPiNumber = 3.14159265;

for some historical reason 'const float' is not known at compile time. To make it work, you must change this line to:

constexpr float kPiNumber = 3.14159265;

Here is the complete code:

namespace {
   const int kLength = 1;
   constexpr float kPiNumber = 3.14159265f;
   constexpr float kCircumferenceArc()
   { return (2*kPiNumber*kLength) / 360; }
}
Michael Veksler
  • 8,217
  • 1
  • 20
  • 33
  • "_for some historical reason 'const float' is not known at compile time._" One can make `const` variables, having the values of them, known only at runtime. `constexpr`explicitly states, that the value must be known at compile time. – Algirdas Preidžius Jul 21 '18 at 10:09
  • 1
    I cover the [history of why floating point have exception wrt to constant expression](https://stackoverflow.com/a/30742473/1708801) – Shafik Yaghmour Jul 21 '18 at 14:38