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

2022-01-11 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.

相关文章