6
constexpr int f() { return 0; }
int g() { return 0; }

constexpr auto c1 = f(); // OK
constinit auto c2 = f(); // OK

constexpr auto d1 = g(); // ill-formed
constinit auto d2 = g(); // ill-formed

int main() {}

As illustrated in the code above, I cannot find any difference between constinit and constexpr.

What's the real difference between constinit and constexpr?


Update:

The related What is constinit in C++20? doesn't clearly state the difference between constinit and constexpr.

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • @E_net4thedupefinder, the answer in your link doesn't clearly state the difference between `constinit` and `constexpr`. – xmllmx Jun 18 '20 at 07:30
  • 1
    Yes, it does. The very first answer goes into explicit detail about what `constexpr` entails and how `constinit` does not imply most of those things. – Nicol Bolas Jun 18 '20 at 13:28

1 Answers1

7

A constinit variable is constant initialized, but it is not usable in a constant expression, nor even automatically constant. Your main can legally contain this line

c2 = 2; 

Yup, modification is possible after initialization.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • From cppreference: *"`constexpr` mandates that the object must have static initialization and **constant destruction** and makes the object const-qualified, however, `constinit` does not mandate **constant destruction** and `const`-qualification."* Just for me, can you just hint me what does this **constant destruction** means; just how `constexpr` mandates this and `constinit` is not. – mada Dec 12 '21 at 15:04
  • @AccessDenied - I can't. As far as I can tell this is something that appears only on cppreference, and so may very well be cooked up by whomever edited that entry. – StoryTeller - Unslander Monica Dec 12 '21 at 18:02