Search code examples
csyntaxinitializer-listdesignated-initializer

What does this syntax in an initializer list in C mean?


I was reading bootloader code of some OS and came up with such syntaxt:

pde_t entry_pgdir[NPDENTRIES] = {
        // Map VA's [0, 4MB) to PA's [0, 4MB)
        [0]
                = ((uintptr_t)entry_pgtable - KERNBASE) + PTE_P,
        // Map VA's [KERNBASE, KERNBASE+4MB) to PA's [0, 4MB)
        [KERNBASE>>PDXSHIFT]
                = ((uintptr_t)entry_pgtable - KERNBASE) + PTE_P + PTE_W
};

What does it mean — [0] = …?


Solution

  • This is C99 array initialization syntax (aka ‘designated initializer’). It lets you mix regular values, e.g.

    pde_t entry_pgdir[NPDENTRIES] = {val1, val2}
    

    with [ind1] = val1, [ind2] = val2 syntax. The semantics of this is that the value in square brackets is interpreted as an index, and the value after = is interpreted as the value to store at the corresponding index.

    The remaining entries are zeroed out. If you put regular values after an indexed one, the numbering continues at index+1.

    This syntax is convenient when the data has gaps, for example

    int logval[] = {
        [1<<0] = 1
    ,   [1<<1] = 2
    ,   [1<<2] = 3
    ,   [1<<3] = 4
    ...
    };
    

    This is easier to read than its plain equivalent:

    int logval[] = {0, 1, 2, 0, 3, 0, 0, 0, 4, ...}