Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

c - 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:

#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
", status());
    printf("second call %d
", status());
    return 0;
}

Note, the purpose of the faulty status() function was to maintain a status. I had expected to get a warning for this with -Wall. I tried also -Wunreachable-code, -Wextra, -pedantic and -ansi (as it was discussed here). Yet, none of those give me a warning.

It appears gcc silently removes the static variable assignment.

In my opinion gcc options -Wall -Werror should throw an error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

gcc 4.4 will give you warning. In the later versions of gcc this feature (-Wunreachable-code) has been removed.

See here: 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. The compiler still accepts and ignores the command line option so that existing Makefiles are not broken. In some future release the option will be removed entirely.

Ian


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...