Search code examples
c++constantsc++23

A value of type "const int*" cannot be used to initialize an entity of type "int* const"


I have this code in c++ on vs 2022 community version.


import std;

int main()
{
    constexpr int x = 10;
    constexpr int* p = &x;
    
    
}

I am not allowed to assign the address of x to p because of this: A value of type "const int*" cannot be used to initialize an entity of type "int* const". So I understand that &x means const int* and p is int* const. Why so? I think p is pointer to const int. It seems constexpr applies to p and not to int. Could you clarify?


Solution

  • constexpr int x = 10; implies int const x = 10;.

    constexpr int* p = &x; implies int* const p = &x; - p is an unchangeable pointer to a changeable int.

    In the generic form constexpr T x = t; implies T const x = t;. It doesn't change a pointee type.

    C++ does not allow to assign an address of a const to a pointer that points to a non const.

    The proper solution in the global context:

    constexpr int x = 10;
    constexpr const int* p = &x;
    

    The proper solution in a function local context:

    int main() {
      static constexpr int x = 10;
      constexpr const int* p = &x;
    }
    

    static is not implied by constexpr and non static constexpr variable is just a usual runtime const variable.