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.

5
  • 9
    atan is not constexpr. See this question. Commented Apr 11, 2017 at 17:44
  • 1
    What book are you using and what page/section is this code in. Commented Apr 11, 2017 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;. Commented Apr 11, 2017 at 17:57
  • can you please share which book is that? Commented Apr 11, 2017 at 17:58
  • 1
    @ΦXocę웃Пepeúpaツ sure, here's the German Amazon link: amazon.de/umfassende-Handbuch-aktuell-Standard-Computing/dp/… Commented Apr 11, 2017 at 18:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.