0

today I was reading dwm source code where I encountered this piece of code:

static void (*handler[LASTEvent]) (XEvent *) = {
  [ButtonPress] = buttonpress,
  [ClientMessage] = clientmessage,
  [ConfigureRequest] = configurerequest,
  [ConfigureNotify] = configurenotify,
  [DestroyNotify] = destroynotify,
  [EnterNotify] = enternotify,
  [Expose] = expose,
  [FocusIn] = focusin,
  [KeyPress] = keypress,
  [KeyRelease] = keypress,
  [MappingNotify] = mappingnotify,
  [MapRequest] = maprequest,
  [MotionNotify] = motionnotify,
  [PropertyNotify] = propertynotify,
  [UnmapNotify] = unmapnotify
};

this is a function pointer array, I get it. but why is it initialized this way? I mean what are all those bracket values inside initialization block? e.g. ([ButtonPress] = buttonpress)

sepisoad
  • 2,201
  • 5
  • 26
  • 37
  • Are they enums or const ints? – Neil May 09 '17 at 15:28
  • 2
    This doesn't look like C code. – Jabberwocky May 09 '17 at 15:29
  • 5
    It's just C99 designated initialisers - the values inside the square brackets are array indices. – Paul R May 09 '17 at 15:30
  • @PaulR, thanks, that's the answer. but what is it good for? – sepisoad May 09 '17 at 15:40
  • 1
    @sepisoad: see the linked answer - it's useful when you only want to initialise particular elements of an array (sparse initialisation) or when you want to decouple the ordering of the elements in the array from the order in which you specify them (for readability, perhaps, or because the order might change later). – Paul R May 09 '17 at 15:44

0 Answers0