20

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\n", status());
    printf("second call %d\n", 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.

brhans
  • 269
  • 2
  • 10
Andreas Haas
  • 201
  • 2
  • 4

2 Answers2

26

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

Jonathon Reinhart
  • 124,861
  • 31
  • 240
  • 314
A. K.
  • 30,148
  • 15
  • 48
  • 80
  • 12
    I hate it when they remove features based on reasons like that. And doing it covertly... *"The compiler still accepts and ignores the command line option"* So after a compiler update we had a bug, that could have been avoided if the compiler had warned... – Calmarius Apr 20 '14 at 16:28
  • 1
    Commit [bc3c12a29c67753c473b465767b2ba6b2f7e72a6](https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=bc3c12a29c67753c473b465767b2ba6b2f7e72a6) if anyone is curious. – Nate Eldredge Feb 02 '21 at 03:29
0

gcc has dozens of passes -- to see them try compiling with switches like

-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. 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. :-)