C23 added a keyword constexpr which can be used to define objects as compile-time constants instead of enumerations or macros. For example:
constexpr int x = 10;
constexpr int y = x+10; // Valid
switch (some_var) {
case y: // Valid
// ...
}
static int z = y; // Valid
Previously only integer constants (sizeof() or enum or literal values such as 10) or addresses of global/static objects could be treated as compile/translation-time constants and a handful of arithmetic operations could be performed on them at compile-time.
Are there any new operations and types can be handled in a constexpr expression in C23? What are the limitations?
Compound literals
constexprcan be used to qualify compound literal:Before C23 there was no support for compile-time constant (Or even
static) compound literals even if all their members were compile-time constant:structandunionconstexprcan be combined with astructorunionto create a compile-time constant object. The members may be read at compile time:This does not permit compile-time type-punning though:
Arrays
There is no way to access the value of any array member at compile time:
But those operators can be used to generate an address of one of the array members as a compile-time constant.
Functions
C++-style
constexprfunctions are not supported. As such no function call can be used in aconstexprexpression.Unsupported operations