Robz Robz - 3 months ago 29
C Question

weird bracket & macro syntax in c

I've tried to articulate this into google, but have failed to find anything useful describing it. Here's the code:

struct Segdesc gdt[] =
{
// 0x0 - unused (always faults -- for trapping NULL far pointers)
SEG_NULL,

// 0x8 - kernel code segment
[GD_KT >> 3] = SEG(STA_X | STA_R, 0x0, 0xffffffff, 0),

// 0x10 - kernel data segment
[GD_KD >> 3] = SEG(STA_W, 0x0, 0xffffffff, 0),

// 0x18 - user code segment
[GD_UT >> 3] = SEG(STA_X | STA_R, 0x0, 0xffffffff, 3),

// 0x20 - user data segment
[GD_UD >> 3] = SEG(STA_W, 0x0, 0xffffffff, 3),

// 0x28 - tss, initialized in trap_init_percpu()
[GD_TSS0 >> 3] = SEG_NULL
};


Can someone explain the meaning of having brackets without an array or pointer in front of them??

Answer

This obscure syntax is called a designated initializer and it lets you skip elements when creating an array aggregate.

Take a look at this program:

#include <stdio.h>
int a[] = {
    1, [2]=3, [5]=7
};
int main() {
    int i;
    for(i=0;i!=sizeof(a)/sizeof(int);i++)
        printf("a[%d] = %d\n", i, a[i]);
    return 0;
}

It uses the same syntax to skip elements 1, 3, and 4 of the array a.

This is what this program prints:

a[0] = 1
a[1] = 0
a[2] = 3
a[3] = 0
a[4] = 0
a[5] = 7

Your program does the same thing, but it initializes an array of structures, and calculating the indexes into its array aggregate using bit shifts of compile-time constants. You can find the values of these indexes in the comments (0x08, 0x10, 0x18, 0x20, and 0x28).

Comments