回答这篇文章时,我建议使用do {...} while(0)多行宏.
在MSVC上,我发现此代码抛出:
warning C4127: conditional expression is constant
Run Code Online (Sandbox Code Playgroud)
为了使代码无警告,我需要选择以下丑陋的替代方案之一:
选项1
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4127)
#endif
code_using_macro_that_generates_C4217;
#ifdef _MSC_VER
#pragma warning(pop)
#endif
Run Code Online (Sandbox Code Playgroud)
选项2
将我的宏定义为:
#define MULTI_LINE_MACRO do { ... } while(0,0)
Run Code Online (Sandbox Code Playgroud)
要么
#define MULTI_LINE_MACRO do { ... } while((void)0,0)
Run Code Online (Sandbox Code Playgroud)
一些程序员也称它为"猫头鹰",(0,0)看起来像一只猫头鹰.
选项3
定义一个新的宏WHILE_0,它不会生成警告而是使用它而不是while(0)
问题
我相信所有选择都或多或少都是可怕的.为什么MSVC会为看似正确的代码生成此警告,并激励我在代码中添加一些丑陋以保持代码警告免费?
我相信条件中的常量表达式是完全有效的,特别是在基于编译器优化代码的能力的构造中.
此外,我没有得到warning C4127像这样的代码:
void foo(unsigned bar)
{
while (bar >= 0)
;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:是不是warning C4127: conditional expression is constant完全没用,是不是它激发了丑陋的代码?这个警告是否有助于编写更好的代码?