Re:C's designated initializers give us named arguments
by robmccoll on Thursday November 19, 2026 @08:21AM
(#50559761)
It's fun watching people rediscover this every so often. If you like this sort of thing, go check out creating generator functions using a switch embedded throughout your function. You can wrap it in macros to end up with a nice yield keyword emulation.
[ Parent
| on HN ]
Re:C's designated initializers give us named arguments
by sunrunner on Thursday November 19, 2026 @08:35AM
(#50559901)
Is this essentially the mechanism behind Duff's Device (switch cases being better thought of as line-oriented jumps instead of structured blocks) but generalised?
Re:C's designated initializers give us named arguments
by mtklein on Thursday November 19, 2026 @08:46AM
(#50560047)
sort of like this,
#include <stdio.h>
static int generator(int st, float *out) {
switch (st++) {
case 0: *out = 1.0f; return st;
case 1: *out = 7.0f; return st;
case 2: *out = 9.0f; return st;
}
return 0;
}
int main(void) {
float f;
for (int st = 0; (st = generator(st, &f));) {
printf("generator yielded %g\n", (double)f);
}
return 0;
}
but notice you also have the option to make the state static rather than a parameter, which gives you more encapsulation of your state machine at the cost of being way less flexible in terms of threading and reentrance.
Re:C's designated initializers give us named arguments
by sunrunner on Thursday November 19, 2026 @08:59AM
(#50560189)
Ah okay, thanks! Surprisingly more readable as there's no loop (in this example...)
Re:C's designated initializers give us named arguments
by lelanthran on Thursday November 19, 2026 @09:01AM
(#50560223)
If you really want readable, search for the protothreads library
Re:C's designated initializers give us named arguments
by bluGill on Thursday November 19, 2026 @09:17AM
(#50560434)
That isn't Duff's device. Duff's device has NO return/break, it intentionally falls through to the next case statement. It is an interesting optimization that is only rarely useful (and probably even less useful in these days of optimization compilers) that everybody misunderstands.
Re:C's designated initializers give us named arguments
by cryptonector on Thursday November 19, 2026 @10:09AM
(#50561122)
And go take a look at:
- the old Icon to-C compiler
- PuTTY's co-routines (and Simon Tatham's essay on C co-routines[0])
[0] https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html