5 ms·
What's the deal with the `while ... while(0)` and `do ... while(0)` macros? Is it some scoping trick? #define TKVDB_EXEC(FUNC) \ do {
by Spiritus 8y ago
What's the deal with the `while ... while(0)` and `do ... while(0)` macros? Is it some scoping trick?
#define TKVDB_EXEC(FUNC) \
do { \
TKVDB_RES r = FUNC; \
if (r != TKVDB_OK) { \
return r; \
} \
} while (0)
#define TKVDB_SKIP_RNODES(NODE) \
while (NODE->c.replaced_by) { \
NODE = NODE->c.replaced_by; \
} while (0)
- jwilk 8y agodo … while(0) is a well-know method of writing multi-statement macros: http://c-faq.com/cpp/multistmt.html http://c-faq.com/cpp/multistmt.html while … while(0) looks like a mistake?
- zambal 8y agoYou are correct. At least the do... while statement is a common c macro trick to make sure a macro has its own scope. The idea is that a compiler will optimize the do....while statement away, so it does not have any runtime overhead. The wile...while(0) statement is new for me (didn't know this is actually legal syntax), but I suspect it's done for similar reasons.
- jwilk 8y ago> didn't know this is actually legal syntax It looks like some unusual looping syntax; but in fact these are just two normal while loops one after another.
- vmxdev 8y agoYes, the first macro is the common trick, and the second is the mistake (wondering, but it works). I update the code. Thanks a lot for pointing it out!