2

I don't know what this "feature" is called so I coudn't google it also I'm sorry if the title doesn't make sense. I recently looked at suckless dwm's source and saw this code: (from dwm.c)

static int (*xerrorxlib)(Display *, XErrorEvent *);

And also this:

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

What does void (*handler[LASTEvent]) (XEvent *) mean ? What it is called and why it is used for ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Zer0day
  • 89
  • 5

1 Answers1

8

This declaration

static int (*xerrorxlib)(Display *, XErrorEvent *);

is a declaration of a pointer to function with the name xerrorxlib that ( the function) has the return type int and two parameters of pointer types Display * and XErrorEvent *.

The pointer has the static storage duration.

This declaration

static void (*handler[LASTEvent]) (XEvent *) = {

declares an array with the name handler of LASTEvent elements of pointers to function with the return type void and the parameter type XEvent *. The array also has the static storage duration.

As for records like this

[ButtonPress] = buttonpress,

then in the square brackets there is an index of the array element that is initialized.

For example you can write

enum { First = 0, Second = 1 };

and then to use the enumerators in the braced init list in an array declaration like

int a[] =
{
    [First] = 10,
    [Second] = 20
};

In this case the array will have two elements where the element with the index 0 is initialized by the value 10 and the element with the index 1 is initialized with the value 20.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So if I didn't get it wrong, it is mapping the LASTEvent to functions, where LASTEvent is the parameter used to index other functions, but what is [ButtonPress], [ClientMessage] and other things inside square brackets ? Why are they like { [ButtonPress] = buttonpress, [ClientMessage] = clientmessage } and not just a the name of the functions like { buttonpress, clientmessage ...} What are the things inside square brackets ? – Zer0day Oct 03 '22 at 19:07
  • 1
    @Zer0day LASTEvent is the number of elements in the declared array. As for elements like [ButtonPress] then in the square brackets there are specified indices of the array that probably were declared as enumerators. – Vlad from Moscow Oct 03 '22 at 19:11