Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 930
Robz Avatar asked Feb 02 '23 08:02

Robz


1 Answers

This is called a designated initializer. It's a C99 feature. It's useful when defining arrays that are mostly zero, with some values at specific indices.

Cribbing examples off the GCC page:

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

is equivalent to

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

"Designated initializer" also refers to the ability to initialize structs in an analogous fashion:

struct point p = { .y = yvalue, .x = xvalue };
like image 93
John Calsbeek Avatar answered Feb 11 '23 13:02

John Calsbeek