principlecppCritical
const vs constexpr on variables
Viewed 0 times
variablesconstexprconst
Problem
Is there a difference between the following definitions?
If not, which style is preferred in C++11?
const double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;If not, which style is preferred in C++11?
Solution
I believe there is a difference. Let's rename them so that we can talk about them more easily:
Both
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.
const double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;Both
PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:constexpr double PI3 = PI1; // errorbut:
constexpr double PI3 = PI2; // okand:
static_assert(PI1 == 3.141592653589793, ""); // errorbut:
static_assert(PI2 == 3.141592653589793, ""); // okAs 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.
Code Snippets
const double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;constexpr double PI3 = PI1; // errorconstexpr double PI3 = PI2; // okstatic_assert(PI1 == 3.141592653589793, ""); // errorstatic_assert(PI2 == 3.141592653589793, ""); // okContext
Stack Overflow Q#13346879, score: 570
Revisions (0)
No revisions yet.