Several varieties of expressions are known asconstant expressions.
Contents |
The expression following#if or#elif must expand to
defined.Character constants, when evaluated in#if-expressions, may be interpreted in the sourcecharacter set, the execution character set, or some other implementation-defined character set.
Integer arithmetic in | (since C99) |
An integer constant expression is an expression that consists only of
sizeof operators whose operands are not VLA(since C99)
| (since C11) |
| (since C23) |
Integer constant expressions are evaluated at compile time. The following contexts require expressions that are known asinteger constant expressions:
case label of aswitch statement
| (since C99) |
| (since C11) |
| (since C23) |
Expressions that are used in theinitializers of objects with static and thread_localstorage durationor declared with theconstexpr storage-class specifier(since C23) must be either string literals or expressions that may be one of the following
sizeof operatorswhose operands are not VLA(since C99)| (since C11) |
| (since C23) |
5) anamed constant which is, an identifier that is
. member access operator to a named constant of structure or union type, even recursively.6) acompound literal constant, which is
Astructure or union constant is a named constant or compound literal constant with structure or union type, respectively. If the member-access operator | (since C23) |
Unlike with integer constant expressions, static initializer expressions are not required to be evaluated at compile time; the compiler is at liberty to turn such initializers into executable code which is invoked prior to program startup.
staticint i=2||1/0;// initializes i to value 1
| This section is incomplete Reason: other mini-examples |
The value of a floating-point static initializer is never less accurate than the value of the same expression executed at run time, but it may be better.
Arithmetic constant expressions of floating-point types that are not used in static initializers are always evaluated as-if during run-time and are affected by thecurrent rounding (ifFENV_ACCESS is on) and report errors as specified inmath_errhandling.
void f(void){#pragma STDC FENV_ACCESS ONstaticfloat x=0.0/0.0;// static initializer: does not raise an exceptionfloat w[]={0.0/0.0};// raises an exceptionfloat y=0.0/0.0;// raises an exceptiondouble z=0.0/0.0;// raises an exception}
If an expression evaluates to a value that is not representable by its type, it cannot be used as a constant expression.
Implementations may accept other forms of constant expressions. However, these constant expressions are not considered as integer constant expressions, arithmetic constant expressions, or address constant expressions, and thus cannot be used in the contexts requiring these kinds of constant expressions. For example,int arr[(int)+1.0]; declares a VLA.
C++ documentation forConstant expressions |