Question

given this function:

int doThings() {
    int x = 1;
    return x;
    x + 1;
    cout << "x: " << x << '\n';
}

Is there a compiler warning flag (g++ or clang++) that can catch the fact the code after return won't be run?

UPDATE:

Running clang++ with -Wunreachable-code did the trick

Was it helpful?

Solution

The gcc compiler (up to 4.4) had a -Wunreachable-code option which should catch this.

This wasn't part of the -Wall group since you're more likely to have unreachable code during the development process, the time when you're most likely to be using -Wall.

It was removed as of 4.5 due to inconsistencies with the optimiser. By removed, I mean the compiler still accepts the flag but doesn't act on it. I believe Clang still includes that option, since it likes to be compatible with gcc.

OTHER TIPS

Clang provides -Wunreachable-code, which will warn for this code (live example).

GCC also provides this option, but it has been silently disabled since gcc 4.5.

x + 1; does nothing, regardless of whether or not it is ever run. This is caught by -Wunused-value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top