4 ms·
Recently started hiding "... do" and "while (0);..." in macros to write nicely bracketed start and end C macros eg this set for generating HTML: https://github
by rwmj 4y ago
Recently started hiding "... do" and "while (0);..." in macros to write nicely bracketed start and end C macros eg this set for generating HTML:
https://github.com/libguestfs/libguestfs-common/blob/master/utils/libxml2-writer-macros.h https://github.com/libguestfs/libguestfs-common/blob/master/...
You can write:
start_element ("memory") {
attribute ("unit", "MiB");
string_format ("%d", g->memsize);
} end_element ();
to generate <memory unit="MiB">1024</memory>
- ttoinou 4y agoWhy do you need to start with while (0); ?
- webstrand 4y agoThat's pretty cool. It's been a while since I've done C, but couldn't you use a `for` loop instead of a while and perform any necessary cleanup in the "update" section? i.e. https://gcc.godbolt.org/z/jq84jondh https://gcc.godbolt.org/z/jq84jondh (The condition is optimized away by the big three: msvc, clang, and gcc)
- billforsternz 4y agoLooks good. I wonder why this trick is invariably implemented with "do {" and "} while (0)" and never with "if(1) {" and "} else" ?
- taspeotis 4y agoI think in part because do … while expects a ; at the end so you are obliged to provide one, which makes the macro feel more like a “real” function call. if … else {} you could omit the ;
- billforsternz 4y agoGood point, thank you. The while (0) demands the expected ; The trailing else hopes for the expected ; but would tolerate a wide range of nonsense instead.
- deleted 4y ago[deleted]