What's the real difference between "constinit" and "constexpr"?

831 Views Asked by At
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.

1

There are 1 best solutions below

2
On BEST ANSWER

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.