Saturday, August 17, 2013

Initializing array in C, C++ and the advantage of compiling with GCC

If your compiler is GCC you can use following syntax:
int array[1024] = {[0 ... 1023] = 5};


To specify an array index, write `[index] =' before the element value. For example,
     int a[6] = { [4] = 29, [2] = 15 };
is equivalent to
     int a[6] = { 0, 0, 15, 0, 29, 0 };
The index values must be constant expressions, even if the array being initialized is automatic.
An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write `[index]' before the element value, with no `='.
To initialize a range of elements to the same value, write `[first ... last] = value'. This is a GNU extension. For example,
     int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

No comments:

Post a Comment