Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a static const and constexpr variable?

I understand that a constexpr variable can be used at compiletime. For a template, or static asser for instance.

But if I want to do that without constexpr I can with static const.

What is since C++11/14 introduced constexpr the difference between

constexpr int a = 3;
//AND
static const int a = 3;

Thank you!

Another way to see this question is which should I use?

like image 509
dzada Avatar asked May 08 '14 09:05

dzada


People also ask

What is the difference between const and constexpr?

The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time.

Is constexpr the same as static const?

constexpr variable is guaranteed to have a value available at compile time. whereas static const members or const variable could either mean a compile time value or a runtime value. Typing constexpr express your intent of a compile time value in a much more explicit way than const .

What is constexpr static?

Static specifies the lifetime of the variable. A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later.

What is constexpr used for?

constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.


1 Answers

The main difference that I know is, the value of constexpr must be known in compile-time while a const static can be assigned in run-time.

const static int x = rand();
like image 188
masoud Avatar answered Sep 22 '22 21:09

masoud