HiveBrain v1.2.0
Get Started
← Back to all entries
principlecppCritical

const vs constexpr on variables

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
variablesconstexprconst

Problem

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?

Solution

I believe there is a difference. Let's rename them so that we can talk about them more easily:

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;  // error


but:

constexpr double PI3 = PI2;  // ok


and:

static_assert(PI1 == 3.141592653589793, "");  // error


but:

static_assert(PI2 == 3.141592653589793, "");  // ok


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.

Code Snippets

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;
constexpr double PI3 = PI1;  // error
constexpr double PI3 = PI2;  // ok
static_assert(PI1 == 3.141592653589793, "");  // error
static_assert(PI2 == 3.141592653589793, "");  // ok

Context

Stack Overflow Q#13346879, score: 570

Revisions (0)

No revisions yet.