lavacode lavacode - 3 months ago 21
C Question

What is this C function syntax?

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.

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