Monday, April 6, 2009

Initializers

Initializers set the initial value that is stored in an object (variables, arrays, structures, and so on). If you don't initialize an object, and it has static duration, it will be initialized by default in the following manner:

To zero if it is an arithmetic type
To null if it is a pointer type

Note: If the object has automatic storage duration, its value is indeterminate.

Syntax for initializers

initializer
= expression
= {initializer-list} <,>}
(expression list)
initializer-list
expression
initializer-list, expression
{initializer-list} <,>}

Rules governing initializers

The number of initializers in the initializer list cannot be larger than the number of objects to be initialized.
The item to be initialized must be an object (for example, an array).
For C (not required for C++), all expressions must be constants if they appear in one of these places:

In an initializer for an object that has static duration.
In an initializer list for an array, structure, or union (expressions using sizeof are also allowed).

If a declaration for an identifier has block scope, and the identifier has external or internal linkage, the declaration cannot have an initializer for the identifier.
If a brace-enclosed list has fewer initializers than members of a structure, the remainder of the structure is initialized implicitly in the same way as objects with static storage duration.

Scalar types are initialized with a single expression, which can optionally be enclosed in braces. The initial value of the object is that of the expression; the same constraints for type and conversions apply as for simple assignments.

For unions, a brace-enclosed initializer initializes the member that first appears in the union's declaration list. For structures or unions with automatic storage duration, the initializer must be one of the following:

An initializer list (as described in Arrays, structures, and unions).
A single expression with compatible union or structure type. In this case, the initial value of the object is that of the expression.

No comments:

Post a Comment