1

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!

7
  • 4
    The address of a local (i.e. stack-based) variable is not known at compile time. Commented Jul 23, 2022 at 23:02
  • 1
    ... Try declaring ch as static to see the difference that makes. Commented Jul 23, 2022 at 23:07
  • But ch is not a common local variable, it is marked as constexpr. I f I understand correctly, this means that it can be evaluated at compile time. If that's true and the compiler evaluates at compile time, then why the address cannot be evaluated? Commented Jul 23, 2022 at 23:10
  • It's still a real variable (albeit const). const char *c = &ch [2];, for example, compiles. Commented Jul 23, 2022 at 23:16
  • 2
    Thanks. I think I understand it now. The constexpr object is still an object that will be created at runtime. The difference between a constexpr object is that its fields might be evaluated at compile-time. Therefore the compiler can shorten the object creation time. But without optimization, the system still need to create the object at runtime. Thanks! Commented Jul 23, 2022 at 23:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.