简体   繁体   English

是否有“条件表达式不变”的gcc警告?

[英]Is there a gcc warning for “conditional expression is constant”?

I've inherited a sizeable codebase where someone, somehow, has written several conditionals like so: 我继承了一个相当大的代码库,不知怎的,有人编写了几个这样的条件:

enum
{
    FOO_TYPE_A,
    FOO_TYPE_B,
    FOO_TYPE_C,
    FOO_TYPE_D
};

void bar(int fooType)
{
    if (fooType == FOO_TYPE_A || FOO_TYPE_B) // <-- This will always be true, since FOO_TYPE_B is nonzero!
    {
        // Do something intended for only type A or B
    }

    // Do things general to A,B,C,D
}

where the condition check should clearly be: 条件检查应该明确是:

    if (fooType == FOO_TYPE_A || fooType  == FOO_TYPE_B)

Is there a warning in gcc I can turn on to find them all, similar to MSDN's C4127 ? 在gcc中是否有警告我可以打开以找到它们,类似于MSDN的C4127

Specifically, I'm using the Android NDK r9d. 具体来说,我使用的是Android NDK r9d。

If not, why not? 如果没有,为什么不呢? It seems like a useful catch-all for unintentional assignment, unsigned > 0 as well as the above foolishness. 对于无意识的赋值,无符号> 0以及上述愚蠢似乎都是有用的。

EDIT: Made the code more verbose to illustrate the problem. 编辑:使代码更详细,以说明问题。

I do not see a warning that corresponds to MSDN C4127. 我没有看到与MSDN C4127相对应的警告。 GCC does have a warning that is somewhat similar in intent, but not to address your problem: -Wtype-limits GCC确实有一个警告,其意图有点类似,但不是为了解决您的问题: -Wtype-limits

Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. 如果由于数据类型的范围有限,比较始终为true或始终为false,则发出警告,但不警告常量表达式。 For example, warn if an unsigned variable is compared against zero with < or >= . 例如,警告是否将unsigned变量与零比较为<>= This warning is also enabled by -Wextra . -Wextra也启用此警告。

As you can see, GCC explicitly states it does not warn about constant expressions. 正如您所看到的,GCC明确声明它不会警告常量表达式。 The motivation for this may be due to the common use of constant expressions to leverage the compiler's dead code elimination so that macros (or portions of it) can be optimized away by using a compile time constant. 这样做的动机可能是由于常量表达式的共同使用来利用编译器的死代码消除,因此可以通过使用编译时常量来优化宏(或其部分)。 It would be used as an alternative to conditional compilation ( #if defined() and #if X == Y ), as the macro reads more naturally like a regular function. 它将被用作条件编译( #if defined()#if X == Y )的替代,因为宏更像是常规函数。 As a hypothetical example: 作为一个假设的例子:

#define VERIFY(E) \
do { \
    if (NO_VERIFY) break; \
    if (!(E) && (VERIFY_LOG_LEVEL >= log_level() || VERIFY_LOG_ALWAYS)) { \
        log("validation error for: " #E); \
    } \
} while (0)

I think the problem is that variable is a define or a const. 我认为问题是变量是一个定义或一个const。 CONSTANT_2 is a non-zero constant also make this problem. CONSTANT_2是一个非零常数也会产生这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM