6.9 Constant Expressions

A constant expression is an expression that contains only constants. A constant expression can be evaluated during compilation rather than at run time, and can be used in any place that a constant can occur. In the following example, limit+1 is a constant expression, and is evaluated at compile time:

#define limit 500
char x[limit+1]

A constant expression cannot contain assignment, increment, decrement, function-call, or comma operators, except when they are within the operand of a sizeof operator. Each constant expression must evaluate to a constant that is in the range of representable values for its type.

There are several contexts in which C requires an expression that must evaluate to a constant:

6.9.1 Integral Constant Expressions

An integral constant expression has an integral type and contains only operands that are integer constants, enumeration constants, character constants, sizeof expressions, or floating constants that are the immediate operands of casts. Cast operands in an integral constant expression only convert arithmetic types to integral types, except as part of an operand to the sizeof operator.

C allows more latitude for constant expressions in initializers. Such a constant expression can evaluate to one of the following:

6.9.2 Arithmetic Constant Expressions

An arithmetic constant expression has an arithmetic type and contains only operands that are integer constants, floating constants, enumeration constants, character constants, or sizeof expressions. Cast operators in an arithmetic constant expression only convert arithmetic types to arithmetic types, except as part of an operand to the sizeof operator.

6.9.3 Address Constants

An address constant is a pointer to an lvalue designating an object of static storage duration (see Section 2.10), or to a function designator. Address constants must be created explicitly by using the unary & operator, or implicitly by using an expression of array or function type. The array subscript [] and member access operators . and ->, the address & and indirection * unary operators, and pointer casts can be used to create an address constant, but the value of an object cannot be accessed by use of these operators.


Previous Page | Next Page | Table of Contents | Index