2

I have two variables outside of any functions (having the fixed address):

constexpr int j = 1;
const int k = 2;

Then I get their address in main:

int main(){
   constexpr int *p1 = &j; // ok
   constexpr int *p2 = &k; //error: incompatible pointer types of `int*` and const int*
   return 0;
}

I know that constexpr means it can be determined at compile time, and also implies const .

I think if j is a const, p1 should be:

constexpr const int *p1 = &j;

And constexpr const int *p2 = &k works well as expected.

Then, why is constexpr int *p2 = &k wrong while constexpr const int *p2 = &k is ok ?

chenzhongpu
  • 6,193
  • 8
  • 41
  • 79
  • I guess that page doesn't really solve my questions. `constexpr int *p1` means **p1 is a const pointer to int**, and not `a pointer to const int`. – chenzhongpu Jul 18 '15 at 07:26
  • Or in other words, **why is `constexpr int *p2 = &k` wrong while `constexpr const int *p2 = &k;` is ok ?** – chenzhongpu Jul 18 '15 at 07:30
  • 1
    `constexpr` always applies to the thing being declared - it modifies the pointer. In your case, `const` modifies the pointee. – T.C. Jul 18 '15 at 07:36

0 Answers0