c++ - 是否有针对 "conditional expression is constant"的 gcc 警告?

标签 c++ c gcc android-ndk

我继承了一个相当大的代码库,其中有人以某种方式编写了几个这样的条件:

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
}

条件检查应该明确在哪里:

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

在gcc中有没有警告我可以打开找到它们,类似于MSDN的C4127

具体来说,我使用的是 Android NDK r9d。

如果不是,为什么不呢?对于无意赋值,unsigned > 0 以及上述愚蠢行为,这似乎是一个有用的包罗万象。

编辑:使代码更加冗长以说明问题。

最佳答案

我没有看到对应于 MSDN C4127 的警告。 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. 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)的替代方法,因为宏读起来更像常规函数。作为一个假设的例子:

#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)

关于c++ - 是否有针对 "conditional expression is constant"的 gcc 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852364/

相关文章:

c - 在库和程序之间共享变量

macos - 如何在 Mac OSX 下使用 gcc 设置可执行文件的运行时路径(-rpath)?

c++ - GCC 共享库问题

c++ - 向下转型最佳实践 (C++)

c++ - gdb:如何将共享库的日志文件重定向到 gdb 输出

c++ - 先进先出实现

c++ - 有什么方法可以确保我的函数是最后一个被调用的函数吗?

c - 输出是错误的,但我无法查明错误

C uint16 整数或字符格式?

c - 错误: ‘else’ without a previous ‘if’ with fprintf