An expression that
matches the grammar of conditional-expression and is based only on
constants, such as 6 + 4
, is a
constant expression, and can be evaluated by the
compiler. It can
have no operators with side-effects, nor make any function calls. An
expression such as &x
is constant
if x
is a static
object or the name of a function. _Alignof
expressions and
NULL
are also constant.
- constant-expression
conditional-expression
- constant
integer-constant
floating-constant
enumeration-constant
character-constant
- string-literal
encoding-prefix " s-char-sequenceopt "
sizeof
also produces a constant
expression, so long as no part of its operand needs to be
evaluated to compute it. So sizeof n
should be fine, but not
sizeof(int[n])
, unless
n
is also a constant expression.
sizeof
can also ‘hide’ a non-constant
expression within it, and still be a constant expression,
e.g.,
sizeof (x++ * f())
. The increment is not
performed, nor is the function called, as these are not
required to determine the type of the expression, and thus that type's
size.
A constant expression is required in several contexts:
- the condition of
#if
and#elif
, - the length of an array before C99 or if
__STDC_
is defined,NO_ VLA__ - the value of an enumeration constant,
- the width of a bit-field in a structure.
Many of these contexts also require that the expression is of integer type, or impose further constraints.
Note that unmodifiable l-values do not count as constant expressions.