← Thu, Nov 19 digest

C's designated initializers give us named arguments

read article ↗ hn thread ↗

Combining C99 designated initializers and macros enables named, defaultable arguments in C functions, offering an alternative to traditional positional parameters.

summary is enough The core technique is neatly demonstrated, but the comment thread provides crucial context on practical alternatives and hidden footguns.

summary

The article demonstrates how C99 designated initializers combined with macros can simulate named and defaultable arguments with natural function-call syntax. It highlights unique C features like out-of-order initialization and designator overriding that C++ lacks, alongside real-world uses in projects like raddebugger. While clever, the approach involves passing structs by value and preprocessor overhead. Commenters debate its safety, performance impact, and simpler alternatives.

key points

  1. Macros combined with compound literal designated initializers allow C functions to accept named arguments with default values.
  2. C permits designated initializers in any order and allows duplicate designators where the final one takes precedence.
  3. Passing structs by value and the risk of omitting mandatory parameters make this pattern a debated choice for production code.

who should read it

Systems programmers and C developers interested in advanced language idioms and API design.

discussion mixed

consensus

Commenters appreciate the cleverness of the macro hack but generally agree it is too heavyweight and risky for routine use compared to simpler alternatives.

pushback

A few argue that the pattern introduces unnecessary struct-passing overhead and acts as a footgun for missing parameters or accidental overrides.

best comment by flohofwoe ↗

Tbh I would skip all the preprocessor magic proposed in the article and just go for plain C99 'option bag struct' arguments, the called function only needs to be aware that "zero means default".

I've been using this style for almost 10 years now in the sokol headers, and it still feels like the right thing to do and actually more ergonomic than most other languages for initializing complex structs, e.g. see here for creating a 3D render pipeline object with dozens of creation options, but most of them keeping their default values:

state.pip = sg_make_pipeline(&(sg_pipeline_desc){ .layout = …

It demonstrates a cleaner, macro-free alternative using plain C99 option bag structs that is widely used in production header libraries.

Generated by an LLM from the article and thread. Check the sources before relying on it.