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:
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).
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:
You initialize arrays and structures (at declaration time, if you like) with a brace-enclosed list of initializers for the members or elements of the object in question. The initializers are given in increasing array subscript or member order. You initialize unions with a brace-enclosed initializer for the first member of the union. For example, you could declare an array days, which counts how many times each day of the week appears in a month (assuming that each day will appear at least once), as follows:
int days[7] = { 1, 1, 1, 1, 1, 1, 1 }
The following rules initialize character arrays and wide character arrays:
char name[] = { "Unknown" };
which sets up an eight-element array, whose elements are 'U' (for name[0]), 'n' (for name[1]), and so on (and including a null terminator).
struct mystruct { int i; char str[21]; double d; } s = { 20, "Borland", 3.141 };
Complex members of a structure, such as arrays or structures, can be initialized with suitable expressions inside nested braces.
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|