Initializers

An initializer is an optional part of a data declaration that specifies an initial value of a data object.

The initializer consists of the = symbol followed by an initial expression or a braced list of initial expressions separated by commas. The number of initializers must not be more than the number of elements to be initialized. An initializer list with fewer initializers than elements, can end with a comma, indicating that the rest of the uninitialized elements are initialized to zero. The initial expression evaluates to the first value of the data object.

To assign a value to a scalar object, use the simple initializer: expression. For example, the following data definition uses the initializer = 3 to set the initial value of group to 3:

int group = 3;

For unions and structures, the set of initial expressions must be enclosed in { } (braces) unless the initializer is a string literal. If the initializer of a character string is a string literal, the { } are optional. Individual expressions must be separated by commas, and groups of expressions can be enclosed in braces and separated by commas.

In an array, structure, or union initialized using a brace-enclosed initializer list, any members or subscripts that are not initialized are implicitly initialized to zero of the appropriate type.

In the following example, only the first eight elements of the array grid are explicitly initialized. The remaining four elements that are not explicitly initialized are initialized as if they were explicitly initialized to zero.

static short grid[3] [4] = {0, 0, 0, 1, 0, 0, 1, 1};

The following example is an equivalent initialization of the array grid:

static short grid[3] [4] = {{0, 0, 0, 1},
                           {0, 0, 1, 1}};

The initial values of grid are:

Element Value Element Value
grid[0][0] 0 grid[1][2] 1
grid[0][1] 0 grid[1][3] 1
grid[0][2] 0 grid[2][0] 0
grid[0][3] 1 grid[2][1] 0
grid[1][0] 0 grid[2][2] 0
grid[1][1] 0 grid[2][3] 0

 



Declarations Overview
Block Scope Data Declarations
File Scope Data Declarations
Declarators
Storage Class Specifiers
Type Specifiers