samedi 28 février 2015

Practical differences between "do {...} while (0)" and "{...} (void)0" in macros?

It's common practice in C to use:



#define FOO() do { /* body */ } while (0)


While this is fine, it's also possible to do:



#define FOO() { /* body */ }((void)0)


Note: This is quite different from:



#define FOO() if (1) { /* body */ } else


... which has the obvious pitfall of unintentionally affecting the flow-control for the caller, if a semicolon is accidentally left out.




{...}((void)0) has many of the same benefits: you can't accidentally merge logic, and a ; is required at the end of the line, so odd expressions like this don't go by un-noticed: FOO() else {...}.


The only difference I've noticed is it means you need to use braces in if-statements.



if (a)
FOO();
else
BAR();


Must be written as:



if (a) {
FOO();
} else {
BAR();
}


Other then this quirk, it seems to work well, preventing the same kinds of problems do/while method is typically used for.


Are there any significant differences between the 2 methods?


Said differently, if you see a code-base using {...}((void)0), are practical reasons to switch to using do{..}while(0), besides the one difference already noted?




Since this has been asked this has been marked to close as opinion based, note that I'm asking about practical differences - *not* about opinions or which is *best*.


Aucun commentaire:

Enregistrer un commentaire