C++20: constexpr, consteval, constinit - The three musketeers | SoloLearn: Learn to code for FREE!


C++20: constexpr, consteval, constinit - The three musketeers

C++20 adds new keywords consteval and constinit. To get this out of the way, I understand that constexpr is for something that is evaluated at compile time. Not to be confused with const which can be for a constant evaluated at runtime. In relation to constexpr, what is the purpose of constinit and consteval? when and how to use them?

1/23/2021 2:08:11 AM

#define CPP ChillPill

6 Answers

New Answer


constexpr is evaluated at compile-time , only when all of the arguments are constant expressions, otherwise it can be evaluated at runtime also. consteval (was spelled "constexpr!" in previous revision papers) make sure that function must be evaluated at compile time only. On the other hand *constinit* is meant to be applied on variables with static storage duration, to make sures that all of them are initialised at compile time only ( removing the possibility of having "static initialization order fiasco" where initialisation of one static object require other static variable to be initialised which happens to be in different compilation unit which unluckily could not be constructed by then )


That being said you can't use all of them on one variable as according to cppreference (link shared by George Ryan ) " At most one of the constexpr, consteval, and constinit keyword shall appear in decl-specifier-sequence " And it makes sense as consteval is just forced constexpr at compile-time and if you look closely, you can easily see that constexpr kindof implies constinit also.


ok so consteval is compile time. constinit is for static variables only, initialized at compile time? constexpr is also evaluated at compile time but not always if dependencies are not all constexpr? Arsenic


https://en.cppreference.com/w/cpp/language/consteval https://en.cppreference.com/w/cpp/language/constinit


ChillPill indeed, you got that right !


Can someone solve a code in c# tomorrow?