0

cppreference.com says:

A constexpr specifier used in an object declaration implies const.

But I tried to make a constexpr pointer hold the address of a const object of the same base-type but the compiler gave me an error:

const int a = 1;
int main(){
constexpr int *b = &a;
return 0;
}

So, what types can a constexpr pointer point to?

Community
  • 1
  • 1
Mason
  • 501
  • 3
  • 11

2 Answers2

1

The issue here is not with constexpr. If you said

int *b = &a;

You'd get the same error. i.e. "invalid conversion from const int* to int*"

We can fix that by making it a pointer to a const int.

int const *b = &a;

Now we can add constexpr, and yes, constexpr does imply const

constexpr int const *b = &a;

where b is in fact const. This is exactly the same as the following

constexpr int const * const b = &a;
                    //^^^^^
// this const is made redundant by the constexpr.
cigien
  • 57,834
  • 11
  • 73
  • 112
0

Your example doesn't compile because 'a' is a 'const int', and requires a 'constexpr const int' pointer to point to it.

Zuodian Hu
  • 979
  • 4
  • 9