Constexpr initialization with pointers

I am trying to initialize a constexpr declaration with a pointer to an int, which is a const object. I am also trying to define an object with an object that is not of type const.

the code:

#include <iostream> int main() { constexpr int *np = nullptr; // np is a constant to int that points to null; int j = 0; constexpr int i = 42; // type of i is const int constexpr const int *p = &i; // p is a constant pointer to the const int i; constexpr int *p1 = &j; // p1 is a constant pointer to the int j; } 

g ++ log:

 constexpr.cc:8:27: error: '& i' is not a constant expression constexpr.cc:9:22: error: '& j' is not a constant expression 

I believe this is because objects basically do not have fixed addresses, so g ++ returns me error messages; how to fix it? Without the use of literals.

+7
source share
1 answer

Make them static to fix their addresses:

 int main() { constexpr int *np = nullptr; // np is a constant to int that points to null; static int j = 0; static constexpr int i = 42; // type of i is const int constexpr const int *p = &i; // p is a constant pointer to the const int i; constexpr int *p1 = &j; // p1 is a constant pointer to the int j; } 

This is known as an expression for the address constant [5.19p3]:

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

+8
source

All Articles