News for hackers. Stuff that matters.
Re:The Preprocessor Iceberg Meme by rwmj on Thursday July 14, 2022 @02:17PM (#32099609)
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/...

You can write:

  start_element ("memory") {
    attribute ("unit", "MiB");
    string_format ("%d", g->memsize);
  } end_element ();
to generate <memory unit="MiB">1024</memory>
Re:The Preprocessor Iceberg Meme by webstrand on Thursday July 14, 2022 @03:48PM (#32100680)
That'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

(The condition is optimized away by the big three: msvc, clang, and gcc)

Re:The Preprocessor Iceberg Meme by billforsternz on Thursday July 14, 2022 @05:31PM (#32101701)
Looks good. I wonder why this trick is invariably implemented with "do {" and "} while (0)" and never with "if(1) {" and "} else" ?
Re:The Preprocessor Iceberg Meme by taspeotis on Thursday July 14, 2022 @05:53PM (#32101902)
I 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 ;

Re:The Preprocessor Iceberg Meme by billforsternz on Thursday July 14, 2022 @06:07PM (#32102029)
Good 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.
Re:The Preprocessor Iceberg Meme by ttoinou on Thursday July 14, 2022 @03:19PM (#32100389)
Why do you need to start with while (0); ?
Re:The Preprocessor Iceberg Meme by calahad on Thursday July 14, 2022 @03:24PM (#32100454)
Re:The Preprocessor Iceberg Meme by ttoinou on Saturday July 23, 2022 @07:35AM (#32202382)

  #define end_element()    \
    while (0);     \
    do {      \
   if (xmlTextWriterEndElement (xo) == -1) { \
     xml_error ("xmlTextWriterEndElement"); \
   }      \
    } while (0)


Talking about the first while (0);