是否存在针对“条件表达式为常数"的gcc警告? [英] Is there a gcc warning for "conditional expression is constant"?

查看:192
本文介绍了是否存在针对“条件表达式为常数"的gcc警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个相当大的代码库,有人在某种程度上以某种方式编写了以下条件代码:

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)

在gcc中是否存在警告,我可以打开所有内容,类似于MSDN的

Is there a warning in gcc I can turn on to find them all, similar to MSDN's C4127?

具体地说,我正在使用Android NDK r9d.

Specifically, I'm using the Android NDK r9d.

如果没有,为什么不呢?对于无意分配,无符号> 0以及上述愚蠢行为,这似乎是一个有用的包罗万象.

If not, why not? It seems like a useful catch-all for unintentional assignment, unsigned > 0 as well as the above foolishness.

编辑:使代码更详细,以说明问题.

Made the code more verbose to illustrate the problem.

推荐答案

我没有看到与MSDN C4127相对应的警告. GCC确实有一个意图类似的警告,但并未解决您的问题:

I do not see a warning that corresponds to MSDN C4127. GCC does have a warning that is somewhat similar in intent, but not to address your problem: -Wtype-limits

警告由于比较,比较是始终为真还是始终为假 数据类型范围有限,但不警告常量 表达式.例如,警告是否比较unsigned变量 用<>=相对于零.此警告也可通过以下方式启用 -Wextra.

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. For example, warn if an unsigned variable is compared against zero with < or >=. This warning is also enabled by -Wextra.

如您所见,GCC明确声明不会警告常量表达式.这样做的动机可能是由于常使用常量表达式来利用编译器的无效代码消除功能,因此可以通过使用编译时间常量来优化宏(或其部分).它可以用作条件编译(#if defined()#if X == Y)的替代方法,因为宏的读取更自然,就像常规函数一样.作为一个假设的例子:

As you can see, GCC explicitly states it does not warn about constant expressions. 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. 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)

这篇关于是否存在针对“条件表达式为常数"的gcc警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆