![]() |
VOOZH | about |
Standard C90 requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized.
In ISO C99 you can give the elements in random order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well. This extension is not implemented in GNU C++.
To specify an array index, write ‘[index] =’ or '[index]' before the element value. For example,
int a[6] = {[4] = 29, [2] = 15 }; or
int a[6] = {[4]29 , [2]15 };
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 };
Note:- The index values must be constant expressions.
To initialize a range of elements to the same value, write ‘[first ... last] = value’. For example,
int a[] = {[0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
Source : gcc.gnu.org
Output:
1 2 3 10 10 10 10 10 10 10 80 15 0 0 0 0 0 0 0 0 50 400
Explanation:
Note:-
Output:
71
Explanation:
If the size of the array is not given, then the largest initialized position determines the size of the array.
In structure or union:
In a structure initializer, specify the name of a field to initialize with ‘.fieldname =’ or ‘fieldname:’ before the element value. For example, given the following structure,
struct point { int x, y; };
the following initialization
struct point p = { .y = 2, .x = 3 }; or
struct point p = { y: 2, x: 3 };
is equivalent to
struct point p = { 3, 2 };
Output:
x = 2, y = 0, z = 1 x = 20
We can also combine designated initializers for arrays and structures.