cfunction-pointersdeclarationctor-initializer

C double parentheses


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 ?


Solution

  • 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.