Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is constexpr in C++?

I am really confused about a constexpr concept, as I have read constexpr is evaluated at compile time, so it is useful for performance optimization versus normal const.

constexpr int i = 0;
constexpr int& ri = i;

The above code returns an error "invalid initialization of reference of type 'int&' from expression of type 'const int'", why?

Also, the next code has an error:

constexpr int i = 0;
constexpr int* ri = &i;

If I replaced the constexpr keyword with const, all above worked correctly.

like image 961
Bassam Najeeb Avatar asked Feb 08 '17 08:02

Bassam Najeeb


People also ask

When to use #define vs constexpr?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.

What is constexpr static?

static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

What does constexpr constructor mean?

A constructor that is declared with a constexpr specifier is a constexpr constructor. Previously, only expressions of built-in types could be valid constant expressions. With constexpr constructors, objects of user-defined types can be included in valid constant expressions.

Does constexpr improve performance?

Using constexpr to Improve Security, Performance and Encapsulation in C++ constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization.


1 Answers

constexpr int i = 0;
constexpr int  * ri = &i;

The second line is a problem because the pointer does not point to a const object. The pointer itself is const.

Using

constexpr int i = 0;
constexpr int const * ri = &i;

solves that problem. However, that will be still a problem if the variables are defined in a function scope.

constexpr int i = 0;
constexpr int const* ri = &i;

int main() {}

is a valid program.

void foo()
{
   constexpr int i = 0;
   constexpr int const* ri = &i;
}

int main() {}

is not a valid program.

Here's what the C++11 standard has to say about address constant expression:

5.19 Constant expressions

3 .. An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.

like image 147
R Sahu Avatar answered Oct 12 '22 22:10

R Sahu