Initialization of arrays

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ({ }). The initializer is preceded by an equal sign (=). You do not need to initialize all elements in an array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The same applies to elements of arrays with static storage duration. (All file-scope variables and function-scope variables declared with the static keyword have static storage duration.)

There are two ways to specify initializers for arrays:

Using C89-style initializers, the following definition shows a completely initialized one-dimensional array:

static int number[3] = { 5, 7, 2 };

The array number contains the following values: number[0] is 5, number[1] is 7; number[2] is 2. When you have an expression in the subscript declarator defining the number of elements (in this case 3), you cannot have more initializers than the number of elements in the array.

The following definition shows a partially initialized one-dimensional array:

static int number1[3] = { 5, 7 };

The values of number1[0] and number1[1] are the same as in the previous definition, but number1[2] is 0.

Instead of an expression in the subscript declarator defining the number of elements, the following one-dimensional array definition defines one element for each initializer specified:

static int item[ ] = { 1, 2, 3, 4, 5 };

The compiler gives item the five initialized elements, because no size was specified and there are five initializers.



[ Top of Page | Previous Page | Next Page | Contents | Index ]