在有条件的前pression常量值 [英] Constant value in conditional expression
问题描述
在一个编码风格问题有关无限循环的,有些人提到他们preFER的为(;;)的风格,因为一段时间(真)的风格提供了有关条件的前pression上MSVC警告信息是不变的。
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.
这让我很吃惊很大,因为在条件前pressions使用的常量值是避免#IFDEF地狱的有效途径。例如,你可以在你的头:
This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header:
#ifdef CONFIG_FOO
extern int foo_enabled;
#else
#define foo_enabled 0
#endif
而code可以简单的使用条件,并相信编译器的的Elid死code没有定义CONFIG_FOO时:
And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG_FOO isn't defined:
if (foo_enabled) {
...
}
而不必每次测试CONFIG_FOO的foo_enabled使用:
Instead of having to test for CONFIG_FOO every time foo_enabled is used:
#ifdef CONFIG_FOO
if (foo_enabled) {
...
}
#endif
此设计模式用于所有的时间在Linux内核中(例如,在include / linux / cpumask.h定义了几个宏为1或0时,SMP被禁用,并在启用SMP函数调用)。
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).
什么是针对MSVC警告的原因吗?此外,有没有更好的办法来避免#IFDEF地狱,而无需禁用警告?还是一个过于笼统的警告应该不是一般的启用?
What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?
推荐答案
一个警告并不自动意味着code是的坏的,只是可疑的。
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.
这篇关于在有条件的前pression常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!