2

I'm currently getting into more C++11 stuff and jumped about constexpr. In one of my books it's said that you should use it for constants like π for example in this way:

#include <cmath>

// (...)

constexpr double PI = atan(1) * 4;

Now I wanted to put that in an own namespace, eg. MathC:

// config.h

#include <cmath>

namespace MathC {
    constexpr double PI = atan(1) * 4;
    // further declarations here
}

...but here IntelliSense says function call must have a constant value in a constant expression.

When I declare PI the following way, it works:

static const double PI = atan(1) * 4;

What is the actual reason the compiler doesn't seem to like constexpr but static const here? Shouldn't constexpr be eligible here, too, or is it all about the context here and constexprshouldn't be declared outside of functions?

Thank you.

tai
  • 477
  • 1
  • 5
  • 16
  • 8
    [`atan`](http://en.cppreference.com/w/cpp/numeric/math/atan) is not `constexpr`. See [this question](http://stackoverflow.com/questions/17347935/constexpr-math-functions). – François Andrieux Apr 11 '17 at 17:44
  • 1
    What book are you using and what page/section is this code in. – NathanOliver Apr 11 '17 at 17:44
  • So it seems like this is a mistake by the book author then. It's a german book called "C++ - Das umfassende Handbuch" by Jürgen Wolf, published in Rheinwerk Computing, 2nd edition in 2014, page 250. It clearly says `constexpr double PI_V3 = atan(1)*4;`. – tai Apr 11 '17 at 17:57
  • can you please share which book is that? – ΦXocę 웃 Пepeúpa ツ Apr 11 '17 at 17:58
  • 1
    @ΦXocę웃Пepeúpaツ sure, here's the German Amazon link: https://www.amazon.de/umfassende-Handbuch-aktuell-Standard-Computing/dp/3836220210 – tai Apr 11 '17 at 18:00

1 Answers1

5

What is the actual reason the compiler doesn't seem to like constexpr but static const here?

A constexpr must be evaluatable at compile time while static const does not need to be.

static const double PI = atan(1) * 4;

simply tells the compiler that PI may not be modified once it is initialized but it may be initialized at run time.

R Sahu
  • 204,454
  • 14
  • 159
  • 270