4

We just found an issue in our code base, where a statement is after a return statement.

e.g.

std::string MyClass::addElement(Type1 &item, const std::string &param2)
{
    if (param2.empty())
    {
        // logging
        return "";
    }

    return m_database->addElement(item, param2, item.status, true);

    // here I would expect an unreachable code warning
    m_database->updateTableA(item.p1, item.p2, item.p3, AType::AType23);
}

What I don't understand, why our compiler (GCC 4.8.5 and 7) does not emit a warning?

We compile with -std=c++0x -Wall -Wextra -Wsign-compare -Wunknown-pragmas -Wold-style-cast -Wshadow -Wfatal-errors

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Simon
  • 1,616
  • 2
  • 17
  • 39
  • I guess it must be a compile time error. BTW why don't you update your GCC, current version is 8.2 – Victor Gubin Oct 23 '18 at 09:06
  • 1
    [-Wunreachable-code warning removed](http://gcc.gnu.org/ml/gcc-help/2011-05/msg00360.html) – user7860670 Oct 23 '18 at 09:06
  • @VTT thanks for the info. So are there any compilers/tools, which check this? We also use cppcheck and clang-tidy, but both didn't warn either – Simon Oct 23 '18 at 09:08
  • 3
    @VictorGubin Switching to different gcc version (especially when dealing with outdated systems) is not trivial. – user7860670 Oct 23 '18 at 09:08
  • @VictorGubin GCC 4.8.5 is most current on CentOS 7. – Simon Oct 23 '18 at 09:09
  • 1
    VC++ issues `warning C4702: unreachable code` – user7860670 Oct 23 '18 at 09:10
  • Currently not an option, because this code base is for Linux only and won't compile with VC++. – Simon Oct 23 '18 at 09:11
  • @Simon have you tried https://jdhao.github.io/2017/09/04/install-gcc-newer-version-on-centos/ ? – Victor Gubin Oct 23 '18 at 09:11
  • Sightly OT now: we are currently testing https://www.softwarecollections.org/en/scls/rhscl/devtoolset-7/, but not yet in an operational fashion. But GCC 7.2 doesn't check that issue either. – Simon Oct 23 '18 at 09:14
  • BTW, there is another option with [RPM Fusion](https://rpmfusion.org/) – Victor Gubin Oct 23 '18 at 09:14
  • 3
    @VictorGubin That is not even half of the story, horror parts about fighting incompatibilities arising from mixing different binaries / runtimes, building abi bridges, creating statically linked jumbo executables or setting up isolation are missing. – user7860670 Oct 23 '18 at 09:18

1 Answers1

5

GCC cannot emit a warning for dead code, since the Wunreachable-code flag/feature is removed after version 4.4, as you can read here.

Clang version 4 (head is 8 out now, so I don't suggest it), will also emit a warning, when the code is compiled with the [-Wunreachable-code flag:

warning: code will never be executed [-Wunreachable-code]


You could try a static analysis tool, there are plenty of them in that list.

gsamaras
  • 71,951
  • 46
  • 188
  • 305