Search code examples
c++cvisual-c++macroscompiler-warnings

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


I'm often using do-while(0) constructs in my #defines, for the reasons described in this answer. Also, I'm trying to set the compiler's warning level as high as possible to catch more potential problems and make my code more robust and cross-platform. So I'm typically using -Wall with gcc and /Wall with MSVC.

Unfortunately MSVC complains about the do-while(0) construct:

foo.c(36) : warning C4127: conditional expression is constant

What should I do about this warning?

Just disable it globally for all files? It does not seem to be a good idea to me.


Solution

  • 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.