What is this C function syntax?

206 Views Asked by At

I'd say I have intermediate experience with programming in c, however I've never seen this syntax used before to make a function. This reminds me of the syntax for a JQuery event. Overall, I'd like a detailed explanation of what this is and what the alternative syntax could be.A link to where I could read more about this in particular would be great too.

 // Set handlers to manage the elements inside the Window
 window_set_window_handlers(s_main_window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload
  });

This is a code snippet from the Pebble WatchApp tutorial.

2

There are 2 best solutions below

2
dbush On BEST ANSWER

This is a function call making use of a compound literal. It is equivalent to the following:

WindowHandlers temp = {
    .load = main_window_load,
    .unload = main_window_unload
  };
window_set_window_handlers(s_main_window, temp );

The above also makes use of designated initializers, where you can specify fields to initialize by name.

Assuming WindowHandlers contains only load and unload in that order, the above is equivalent to:

WindowHandlers temp = { main_window_load, main_window_unload };
window_set_window_handlers(s_main_window, temp );

The C standard goes into these in more detail.

From section 6.5.2.5:

4 A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

...

9 EXAMPLE 1 The file scope definition

int *p = (int []){2, 4};

initializes p to point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant. The unnamed object has static storage duration.

From section 6.7.8:

1

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }
initializer-list:
    designationopt initializer
    initializer-list , designationopt initializer
designation:
    designator-list =
designator-list:
    designator 
    designator-list  designator
designator:
    [ constant-expression ]
    .identifier

...

7 If a designator has the form

.identifier

then the current object (defined below) shall have structure or union type and the identifier shall be the name of a member of that type.

...

34 EXAMPLE 10 Structure members can be initialized to nonzero values without depending on their order:

div_t answer = { .quot = 2, .rem = -1 };
1
Osama Ashaikh On

This is standard from C99 onwards. It is combining compound literals:

(WindowHandlers) {}

and designated initializers:

.load = main_window_load,
.unload = main_window_unload

See the link What does this dot syntax mean in the Pebble watch development tutorial?