C/C++: How to use the do-while(0); construct without compiler warnings like C4127?

Summary: This warning (C4127) in this particular case is a subtle compiler bug. Feel free to disable it.

In depth:

It was meant to catch situations when logical expression evaluates to a constant in non-obvious situations (such as, if(a==a && a!=a), and somehow, it turned while(true) and other useful constructs into invalid.

Microsoft recommends using for(;;) for infinite loop if you want to have this warning on, and there is no solution for your case. This is one of very few Level-4 warnings my company's development conventions allow to disable.


Perhaps your code needs more owls:

do { stuff(); } while (0,0)

Or the less photogenic but also less warning producing:

do { stuff(); } while ((void)0,0)

As Michael Burr noted in Carl Smotricz' answer, for Visual Studio 2008+ you can use __pragma:

#define MYMACRO(f,g)              \
  __pragma(warning(push))         \
  __pragma(warning(disable:4127)) \
  do { f; g; } while (0)          \
  __pragma(warning(pop))

You can put it on one line (without the \s) if you prefer macros to be unreadable.