Search code examples
c++gcccompiler-warningsdead-code

Code after return statement without warning


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


Solution

  • 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.