Skip to content

Commit

Permalink
Avoid divisions by zero when simplifying numeric calculations.
Browse files Browse the repository at this point in the history
  • Loading branch information
simartin committed Jul 28, 2013
1 parent 09f4d37 commit eb3bf57
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/templatesimplifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,7 @@ bool TemplateSimplifier::simplifyNumericCalculations(Token *tok)
while (tok->tokAt(4) && tok->next()->isNumber() && tok->tokAt(3)->isNumber()) { // %any% %num% %any% %num% %any%
const Token* op = tok->tokAt(2);
const Token* after = tok->tokAt(4);
if (Token::Match(tok, "* %num% /") && tok->next()->str() == MathLib::multiply(tok->strAt(3), MathLib::divide(tok->next()->str(), tok->strAt(3)))) {
if (Token::Match(tok, "* %num% /") && (tok->strAt(3) != "0") && tok->next()->str() == MathLib::multiply(tok->strAt(3), MathLib::divide(tok->next()->str(), tok->strAt(3)))) {
// Division where result is a whole number
} else if (!((op->str() == "*" && (isLowerThanMulDiv(tok) || tok->str() == "*") && isLowerEqualThanMulDiv(after)) || // associative
(Token::Match(op, "[/%]") && isLowerThanMulDiv(tok) && isLowerEqualThanMulDiv(after)) || // NOT associative
Expand Down
10 changes: 10 additions & 0 deletions test/testother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class TestOther : public TestFixture {
TEST_CASE(zeroDiv4);
TEST_CASE(zeroDiv5);
TEST_CASE(zeroDiv6);
TEST_CASE(zeroDiv7); // #4930

TEST_CASE(nanInArithmeticExpression);

Expand Down Expand Up @@ -414,6 +415,15 @@ class TestOther : public TestFixture {
"} } }");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout.str());
}

void zeroDiv7() {
check("void f() {\n"
" int a = 1/2*3/0;\n"
" int b = 1/2*3%0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n"
"[test.cpp:3]: (error) Division by zero.\n", errout.str());
}

void nanInArithmeticExpression() {
check("void f()\n"
Expand Down

0 comments on commit eb3bf57

Please sign in to comment.