[英]Constant value in conditional expression
In a coding style question about infinite loops , some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant. 在关于无限循环的编码风格问题中 ,有些人提到他们更喜欢for(;;)样式,因为while(true)样式在MSVC上给出关于条件表达式是常量的警告消息。
This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. 这让我感到非常惊讶,因为在条件表达式中使用常量值是避免#ifdef地狱的有用方法。 For instance, you can have in your header:
例如,您可以在标题中:
#ifdef CONFIG_FOO
extern int foo_enabled;
#else
#define foo_enabled 0
#endif
And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG_FOO isn't defined: 代码可以简单地使用条件并信任编译器在未定义CONFIG_FOO时删除死代码:
if (foo_enabled) {
...
}
Instead of having to test for CONFIG_FOO every time foo_enabled is used: 每次使用foo_enabled时都不必测试CONFIG_FOO:
#ifdef CONFIG_FOO
if (foo_enabled) {
...
}
#endif
This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled). 这种设计模式一直在Linux内核中使用(例如,include / linux / cpumask.h在禁用SMP时将几个宏定义为1或0,在启用SMP时定义为函数调用)。
What is the reason for that MSVC warning? MSVC警告的原因是什么? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning?
另外,有没有更好的方法来避免#ifdef hell而不必禁用该警告? Or is it an overly broad warning which should not be enabled in general?
或者这是一个过于广泛的警告,一般不应该启用?
A warning doesn't automatically mean that code is bad , just suspicious-looking. 警告不会自动意味着代码很糟糕 ,只是看起来很可疑。
Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. 就个人而言,我从一个能够启用所有警告的位置开始,然后关闭任何证明比使用更令人讨厌的警告。 That one that fires anytime you cast anything to a bool is usually the first to go.
任何时候你向一个布尔施放任何东西的那个人通常是第一个去的。
I think the reason for the warning is that you might inadvertently have a more complex expression that evaluates to a constant without realizing it. 我认为警告的原因是你可能无意中有一个更复杂的表达式,在没有意识到的情况下评估为常量。 Suppose you have a declaration like this in a header:
假设你在标题中有这样的声明:
const int x = 0;
then later on, far from the declaration of x, you have a condition like: 然后,远离x的声明,你有一个像这样的条件:
if (x != 0) ...
You might not notice that it's a constant expression. 您可能没有注意到它是一个常量表达式。
I believe it's to catch things like 我相信这是为了捕捉这样的事情
if( x=0 )
when you meant 当你的意思
if( x==0 )
A simple way to avoid the warning would be: 避免警告的简单方法是:
#ifdef CONFIG_FOO
extern int foo_enabled;
#else
extern int foo_enabled = 0;
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.