C/C++:如何使用 do-while(0);没有像 C4127 这样的编译器警告的构造?

2021-12-22 00:00:00 c macros visual-c++ c++ compiler-warnings

我经常在我的#defines 中使用 do-while(0) 构造,原因如下 在这个答案中.此外,我试图使用来自编译器的尽可能高的警告级别来捕获更多潜在问题并使我的代码更加健壮和跨平台.所以我通常将 -Wall 与 gcc 和 /Wall 与 MSVC 一起使用.

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

不幸的是 MSVC 抱怨 do-while(0) 构造:

Unfortunately MSVC complain about 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 seems to be good idea for me.

推荐答案

总结:在这种特殊情况下的这个警告 (C4127) 是一个微妙的编译器错误.随意禁用它.

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

深入:

它旨在捕捉逻辑表达式在不明显的情况下计算为常量的情况(例如,if(a==a && a!=a),以及以某种方式,它将 while(true) 和其他有用的构造变成无效的.

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 建议使用 for(;;) 进行无限循环,并且没有针对您的情况的解决方案.这是我公司的开发约定允许禁用的极少数 4 级警告之一.

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.

相关文章