简体   繁体   English

为什么 GCC 不对无法访问的代码发出警告?

[英]Why does GCC not warn for unreachable code?

I wonder why gcc (4.6.3) gives me no warning for the unreachable code in this example:我想知道为什么gcc (4.6.3)在这个例子中没有警告我无法访问的代码

#include <stdio.h>

int status(void)
{
    static int first_time = 1;

    if (first_time) {
        return 1;   
        first_time = 0; /* never reached */
    } else {
        return 0;   
    }     
}

int main(int argc, const char *argv[])
{
    printf("first call %d\n", status());
    printf("second call %d\n", status());
    return 0;
}

Note, the purpose of the faulty status() function was to maintain a status.请注意,错误的status()函数的目的是保持状态。 I had expected to get a warning for this with -Wall .我原以为会收到警告-Wall I tried also -Wunreachable-code , -Wextra , -pedantic and -ansi (as it was discussed here ).我也尝试过-Wunreachable-code-Wextra-pedantic-ansi (正如这里讨论的那样)。 Yet, none of those give me a warning.然而,这些都没有给我警告。

It appears gcc silently removes the static variable assignment.看来 gcc 会默默地删除静态变量赋值。

In my opinion gcc options -Wall -Werror should throw an error.在我看来,gcc options -Wall -Werror应该会引发错误。

gcc 4.4 will give you warning. gcc 4.4 会给你警告。 In the later versions of gcc this feature ( -Wunreachable-code ) has been removed.在 gcc 的更高版本中,此功能 ( -Wunreachable-code ) 已被删除。

See here: http://gcc.gnu.org/ml/gcc-help/2011-05/msg00360.html见这里: http : //gcc.gnu.org/ml/gcc-help/2011-05/msg00360.html

The -Wunreachable-code has been removed, because it was unstable: it relied on the optimizer, and so different versions of gcc would warn about different code. -Wunreachable-code已被删除,因为它不稳定:它依赖于优化器,因此不同版本的 gcc 会警告不同的代码。 The compiler still accepts and ignores the command line option so that existing Makefiles are not broken.编译器仍然接受并忽略命令行选项,这样现有的 Makefile 不会被破坏。 In some future release the option will be removed entirely.在未来的某个版本中,该选项将被完全删除。

Ian伊恩

gcc has dozens of passes -- to see them try compiling with switches like gcc 有很多遍——看看它们尝试用像这样的开关编译

-da -dAp -Wa,-a -fdump-ipa-all-all -fdump-tree-all-all -fdump-rtl-all-all -da -dAp -Wa,-a -fdump-ipa-all-all -fdump-tree-all-all -fdump-rtl-all-all

My guess is that some pass has done dead-code elimination before the pass designated to issue the warning in question.我的猜测是,在指定发出相关警告的通行证之前,某些通行证已经完成了死代码消除。 Which could reasonably be considered a bug, but likely the gcc team regard the warning more as a convenience than a moral commitment, and aren't motivated to do a lot of work to make it precise and complete.这可以合理地被认为是一个错误,但 gcc 团队可能更多地将警告视为一种方便而不是道德承诺,并且没有动力做很多工作来使其精确和完整。 If you want to contribute, you could disable optimization passes one-by-one until you find the one preventing the warning, then file a bug report documenting the problem.如果您想做出贡献,您可以逐个禁用优化传递,直到找到阻止警告的优化传递,然后提交记录问题的错误报告。 If that isn't worth your time, maybe fixing it isn't worth their time.如果这不值得你花时间,也许修复它不值得他们花时间。 :-) :-)

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

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