4 ms·
It could help in generic macros, like this: #define SWAP(var1, var2) do { \ auto tmp = var1; \ var1 = var2; \ var2 = tmp; \ } while (0)
by trealira 3y ago
It could help in generic macros, like this:
#define SWAP(var1, var2) do { \
auto tmp = var1; \
var1 = var2; \
var2 = tmp; \
} while (0)
Previously, you would have needed a third macro for the type, or you would have needed to do a byteswap to be generic.
- unwind 3y agoTrue, and now we also get typeof() so there is more than one way! const typeof(var1) tmp = var1;
- kstrauser 3y agoWhy’s that inside do/while?
- asplake 3y agoTo scope the temporaries?
- peterfirefly 3y agoNo, a block would be enough for that. It's to make ; handling natural when the macro is used.
- glouwbug 3y agoForces the use of a semicolon: SWAP(…);
- trealira 3y agoIf you simply put braces around it, you'd generate syntactically invalid code when you don't use braces for if-else statements. Consider this: if (e) SWAP(a, b); else something_else(); Currently, that expands to this, which is still valid code: if (e) do { // ...macro... } while(0); else something_else(); If it were just wrapped in braces, the code would be parsed like this: // One-armed if-statement if (e) { // ...macro... } // Empty statement ; // Another statement else something_else(); It's incorrect syntax to start a statement with else, so the compiler will say something like "Unexpected 'else' at line N."
- _kst_ 3y agohttps://www.c-faq.com/ https://www.c-faq.com/ question 10.4 "What's the best way to write a multi-statement macro?"