3 ms·
I think this author should learn about the "do {} while(0)" trick.
by marcodiego 4y ago
I think this author should learn about the "do {} while(0)" trick.
- HarHarVeryFunny 4y agoWhat's the benefit of do {...} while (0) vs just {...} ?
- tines 4y agoThe latter makes the macro usable without requiring a semicolon, which some people don't like; the former will cause a syntax error if the semicolon is missing, so they feel that it regulates syntax a bit better.
- nice_byte 4y agoWorks if you want to e.g. skip braces if if..else... statements. Some would say putting braces in always is good style, but I like skipping them myself so won't defend it :)
- yakubin 4y agoI agree it’s good style, but surrounding code using bad style is still poor excuse for writing macros which break.
- yakubin 4y agodo {…} while (0) is a statement, so it can be put between “if (…)” and “; else”, while just {…} would result in a syntax error due to a hanging else.
- HarHarVeryFunny 4y agoOK, but I guess what's really being relied on there is that it's syntactically still a single statement when you follow it with ';', whereas {...}; is two statements (which is what breaks the if-else). I just discovered that gcc also supports non-standard "statement expressions" of the form ({...}) which would serve the same purpose at the cost of portability.
- LegionMammal978 4y agoYou can put it inside a braceless if/else statement and follow it with a semicolon. Compare: #define FOO() { ... } #define BAR() do { ... } while (0) In the former case: if (x) FOO(); else ...; // becomes if (x) { ... } ; else ...; In the latter case: if (x) BAR(); else ...; // becomes if (x) do { ... } while (0); else ...;