hn.today

C's designated initializers give us named arguments

quuxplusone.github.io71 points45 comments
Screenshot of C's designated initializers give us named arguments

C’s full designated-initializer rules can be used to simulate named, defaultable function arguments. A macro accepts call-site designators and builds a parameter struct, whose fields are initialized first with defaults and then with caller-provided values. Because C permits designators in any order and lets later initializers for the same field override earlier ones, callers can write calls such as `.kelvin = 373.15, .moles = 2` while omitting values they do not need to change. The example applies this to the ideal gas law, with defaults for pressure, amount of gas, and temperature. Compilers may warn about the intentional duplicate initializers.

Adding a field to the argument struct can extend the function’s options without requiring existing call sites to be rewritten: omitted fields retain their defaults. However, changing the struct changes the ABI, so callers must be recompiled. A shared argument struct can also provide a common set of named options for related functions, and ordinary positional arguments can precede the designated options. Real uses include message-sending helpers and animation parameters in a game-development project. The technique is powerful but heavyweight and unusual; for most functions, ordinary positional parameters are simpler and clearer. It is best reserved for cases where flexible, readable configuration is worth the extra macro and struct machinery.

Read on quuxplusone.github.io45 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

GIMP now has UI tests

GIMP now has UI tests

GIMP has introduced automated UI tests that launch the real application and check common tasks, from opening dialogs to exporting images. The tests run in a hidden desktop on CI servers and use accessibility data, also helping improve screen-reader support. (gimp.org)

PostgreSQL 19

PostgreSQL 19

PostgreSQL 19 adds online table repacking, query-planning advice, faster database operations, and expanded logical replication and standby consistency features. Upgrading requires a migration step, and compatibility changes include removing RADIUS support and enforcing standard-conforming strings. (postgresql.org)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.