Is there a difference between the following definitions?
const double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;
If not, which style is preferred in C++11?
cc++11constantsconstexprvariables
Is there a difference between the following definitions?
const double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;
If not, which style is preferred in C++11?
Best Answer
I believe there is a difference. Let's rename them so that we can talk about them more easily:
Both
PI1
andPI2
are constant, meaning you can not modify them. However onlyPI2
is a compile-time constant. It shall be initialized at compile time.PI1
may be initialized at compile time or run time. Furthermore, onlyPI2
can be used in a context that requires a compile-time constant. For example:but:
and:
but:
As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.