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:

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.


CHaR
Sitemap Supported
Site format updated 2024-06-05T22:37:07.391+0000
Data updated 1970-01-01T00:00:00.000+0000
Page updated 2022-06-17T21:43:05.000+0000