5.3. Constant Expressions
The compiler recognizes constant
expressions
in source code and replaces them with their values. The resulting constant value must be representable in the expression's type. You may use a constant expression wherever a simple constant is permitted.
Operators in constant expressions are subject to the same rules as in other expressions. Because constant expressions are evaluated at translation time, though, they cannot contain function calls or operations that modify variables, such as assignments.
5.3.1. Integer Constant Expressions
An integer
constant expression is a constant expression with any integer type. These are the expressions you use to define the following items:
For example, you may define an array as follows:
#define BLOCK_SIZE 512
char buffer[4*BLOCK_SIZE];
The operands can be integer, character, or enumeration constants, or sizeof expressions. However, the operand of sizeof in a constant expression must not be a variable-length array. You can also use floating-point constants, if you cast them as an integer type.
5.3.2. Other Constant Expressions
You can also use constant expressions to initialize static and external objects. In these cases, the constant expressions can have any arithmetic
or pointer type desired. You may use floating-point constants as operands in an arithmetic constant expression.
A constant with a pointer type, called an address constant, is usually a null pointer, an array or function name, or a value obtained by applying the address operator & to an object with static storage duration. However, you can also construct an address constant by casting an integer constant as a pointer type, or by pointer arithmetic. Example:
#define ARRAY_SIZE 200
static float fArray[ARRAY_SIZE];
static float *fPtr = fArray + ARRAY_SIZE - 1; // Pointer to the last
// array element
In composing an address constant, you can also use other operators, such as . and ->, as long as you do not actually dereference a pointer to access the value of an object. For example, the following declarations are permissible outside any function:
struct Person { char pin[32];
char name[64];
/* ... */
};
struct Person boss;
const char *cPtr = &boss.name[0]; // or: ... = boss.name;
|