Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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>


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)


Looks good. I wonder why this trick is invariably implemented with "do {" and "} while (0)" and never with "if(1) {" and "} else" ?


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 ;


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.


Why do you need to start with while (0); ?



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


Talking about the first while (0);




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

Search: