Strange array initialize expression?

后端 未结 3 679
粉色の甜心
粉色の甜心 2020-11-30 10:15

What is the meaning of following Code? Code is from the regression test suite of GCC.

static char * name[] = {
   [0x80000000]  = \"bar\"
};
相关标签:
3条回答
  • 2020-11-30 10:19

    It's called designated initializer which is introduced in C99, gcc also supports it in GNU89 as an extension, see here for detail.

     int a[6] = { [4] = 29, [2] = 15 };
    

    is equivalent to

     int a[6] = { 0, 0, 15, 0, 29, 0 };
    
    0 讨论(0)
  • 2020-11-30 10:20

    It's a C99 designated initializer. the value in brackets specifies the index to receive the value.

    0 讨论(0)
  • 2020-11-30 10:31

    In C99 you can specify the array indices to assigned value, For example:

    static char * name[] = {
       [3]  = "bar"  
    };
    

    is same as:

    static char * name[] = { NULL, NULL, NULL, "bar"};
    

    The size of array is four. Check an example code working at ideaone. In your code array size is 0x80000001 (its an hexadecimal number).
    Note: Uninitialized elements initialized with 0.

    5.20 Designated Initializers:

    In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well. This extension is not implemented in GNU C++. 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 };
    

    One more interesting declaration is possible in a GNU extension:

    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. For example,

     int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 
    

    Note: that the length of the array is the highest value specified plus one.

    Additionally, we can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a designator applies to the next consecutive element of the array or structure. For example:

     int a[6] = { [1] = v1, v2, [4] = v4 };
    

    is equivalent to

     int a[6] = { 0, v1, v2, 0, v4, 0 };
    

    Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an enum type. For example:

     int whitespace[256]  = { [' '] = 1,  ['\t'] = 1, ['\h'] = 1,
                              ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 
                            };
    
    0 讨论(0)
提交回复
热议问题