Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range Initialization of a C Array

Very simple question of where does this code work?

static void *gostruct[] = 
{
    [0 ... 255] = &&l_bad,
    ['\t'] = &&l_loop, [' '] = &&l_loop, ['\r'] = &&l_loop, ['\n'] = &&l_loop,
    ['"'] = &&l_qup,
    [':'] = &&l_loop,[','] = &&l_loop,
    ['['] = &&l_up, [']'] = &&l_down, // tracking [] and {} individually would allow fuller validation but is really messy
    ['{'] = &&l_up, ['}'] = &&l_down,
    ['-'] = &&l_bare, [48 ... 57] = &&l_bare, // 0-9
    ['t'] = &&l_bare, ['f'] = &&l_bare, ['n'] = &&l_bare // true, false, null
};

Reading through it its clear to see that it initializes an array containing 256 entries to the value &&l_bad and then overrides certain indexes with specific values. But this code does not compile in VS2010 which is what I have access to so I am wondering where this is valid C code.

NOTE: This code snippet was taken from a JSON parser on github that, from my understanding, creates jump tables for the processing of JSON strings.

like image 340
James Avatar asked Oct 18 '11 07:10

James


People also ask

Are arrays in C initialized to 0?

Please note that the global arrays will be initialized with their default values when no initializer is specified. For instance, the integer arrays are initialized by 0 . Double and float values will be initialized with 0.0 . For char arrays, the default value is '\0' .

Do arrays need to be initialized in C?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required.


1 Answers

This construct is called Designated Initializers.
Using Range in Designated Initializers is a GNU gcc specific extension.

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 };

Compiling it with -pedantic shall tell you so.
Note that it is non-portable since it is a compiler specific extension.

like image 53
Alok Save Avatar answered Oct 29 '22 17:10

Alok Save