Why C++ does not allow access address of a constexpr array

Viewed 69

For the following code:

int main()
{
    constexpr char ch[64] = "Hello";
    auto res1 = ch;
    constexpr auto res2 = ch;
}

The assignment of res1 is OK, but the assignment of res2 cannot compile. So this means we can get an address of a compile-time object at run time, but we cannot get the address at compile time. Can you please tell me why C++ block the compilation of that line?

Thanks a lot!

1 Answers

Marking a variable constexpr does not change its storage duration. ch is still a variable local to the function with automatic storage duration and lives only until the end of the function scope. Each time the function is called ch is a new object. ch does not gain static storage duration through the constexpr.

Therefore it is not reasonable to take a pointer to the variable as a constant expression. The value of the pointer would need to be different in every function invocation, violating the assumption that a constant expression evaluates to a single compile-time constant.

If you want the variable to have static storage duration, so that there is only one instance of it in the whole program, then add static in addition to constexpr. The address of static storage duration objects can be used in constant expressions and as result of constant expressions. There is no ambiguity in the pointer value between different instances of the variable.

Related