From 4d070f04e581c590495e8814bcda2295c6e6c082 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 6 Dec 2008 16:25:24 +0000 Subject: [PATCH] Added check that detects unreachable code below a 'return' statement --- CheckOther.cpp | 35 ++++++++++++++++++++++++++++++++++- CheckOther.h | 5 ++++- cppcheck.cpp | 3 +++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/CheckOther.cpp b/CheckOther.cpp index b5d47465c..b36eb1265 100644 --- a/CheckOther.cpp +++ b/CheckOther.cpp @@ -783,5 +783,38 @@ void CheckOther::CheckIncompleteStatement() _errorLogger->reportErr(errmsg.str()); } } -} +} +//--------------------------------------------------------------------------- + + + + + + +//--------------------------------------------------------------------------- +// Unreachable code below a 'return' +//--------------------------------------------------------------------------- + +void CheckOther::unreachableCode() +{ + const TOKEN *tok = TOKEN::findmatch( _tokenizer->tokens(), "[;{}] return" ); + while ( tok ) + { + // Locate the end of the 'return' statement + while ( tok && ! TOKEN::Match(tok, ";") ) + tok = tok->next; + + // Next token should be either "case", "default" or "}" + if (tok && tok->next && !TOKEN::Match( tok, "; case|default|}")) + { + std::ostringstream errmsg; + errmsg << _tokenizer->fileLine(tok->next) << ": Unreachable code below a 'return'"; + _errorLogger->reportErr(errmsg.str()); + } + + // Find the next 'return' statement + tok = TOKEN::findmatch( tok, "[;{}] return" ); + } +} + diff --git a/CheckOther.h b/CheckOther.h index 7e47b02a3..a8b67b8d3 100644 --- a/CheckOther.h +++ b/CheckOther.h @@ -69,7 +69,10 @@ public: void CheckCharVariable(); // Incomplete statement. A statement that only contains a constant or variable - void CheckIncompleteStatement(); + void CheckIncompleteStatement(); + + /** Unreachable code below a 'return' */ + void unreachableCode(); private: void CheckVariableScope_LookupVar( const TOKEN *tok1, const char varname[] ); diff --git a/cppcheck.cpp b/cppcheck.cpp index 99431c73a..7862fe79c 100644 --- a/cppcheck.cpp +++ b/cppcheck.cpp @@ -319,6 +319,9 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) // Check for various types of incomplete statements that could for example // mean that an ';' has been added by accident checkOther.CheckIncompleteStatement(); + + // Unreachable code below a 'return' statement + checkOther.unreachableCode(); } } //---------------------------------------------------------------------------