Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Metaprogramming custom control structures in C (greenend.org.uk)
69 points by rumcajz on April 28, 2015 | hide | past | favorite | 7 comments


Some C hacks have advantages in theory but hard to use effectively, like named+default parameters via struct. Others are practical, but only if you don't care about compilers without GNU extensions (i.e. MSVC), such as RAII via attribute cleanup and safer macros via statement expressions.

This control structure trick, despite being more esoteric looking than any of those, is both useful in practice and standard C. If you're defining a custom data container in C, it will let you write a foreach macro that doesn't require the user to declare any temporaries you need to use, doesn't break the break and continue statements, and doesn't require any weird syntax at the beginning of end of the loop. I highly recommend reading about it.

For a (poorly documented) example of actual use from some code I wrote, see HTAB_FOREACH:

https://github.com/comex/substitute/blob/master/lib/cbit/hta...

and the LET_LOOP macro it uses:

https://github.com/comex/substitute/blob/master/lib/cbit/mis...


I use named parameters in production C code for Nitrogen Logic. It just requires organizing things so that 0 is an acceptable default.


Step 1: Write a Lisp interpreter in C. :)


Actually, probably most frequent users of really weird C preprocessor tricks are lisp implementations. (for the extreme example, CLISP has it's own custom C preprocessor)


Tcl actually has this ability, too, to write control structures in Tcl itself.


Simon Tatham is the author of putty, he knows what he is talking about.


also author of my favourite puzzle collection http://www.chiark.greenend.org.uk/~sgtatham/puzzles/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: