I have a pattern that I based off an answer here & it works on clang, gcc & MSVC. I'm posting it here in the hopes that it'll be useful for others & because the answers here helped me formulate it.
#ifdef WIN32
# define ONCE __pragma( warning(push) ) \
__pragma( warning(disable:4127) ) \
while( 0 ) \
__pragma( warning(pop) )
#else
# define ONCE while( 0 )
#endif
And I use it like this:
do {
// Some stuff
} ONCE;
You can use this in macros too:
void SomeLogImpl( const char* filename, int line, ... );
#ifdef NDEBUG
# define LOG( ... )
#else
# define LOG( ... ) do { \
SomeLogImpl( __FILE__, __LINE__, __VA_ARGS__ ); \
} ONCE
#endif
This also works for the case pointed out above, if F uses 'ONCE' in a function:
#define F( x ) do { f(x); } ONCE
...
if (a==b) F(bar); else someFunc();
Edit: Years later, I realize I forgot to add the pattern I actually wrote this macro for - the "switch-like-a-goto" pattern:
do {
begin_some_operation();
if( something_is_wrong ) {
break;
}
continue_big_operation();
if( another_failure_cond ) {
break;
}
finish_big_operation();
return SUCCESS;
} ONCE;
cleanup_the_mess();
return FAILURE;
This gives you a try/finally-ish construct that's more structured than a crufty goto to your cleanup & return code. Using this ONCE macro instead of while(0) shuts VS up.