Integer division by unsigned

In C++ division of an negative integer by an unsigned integer is implicitely casted to unsigned int first and then divided. This results in a wrong result and will not be detected by the compiler and not by sonar.
This bug cost me more than a week to find

Noncompliant Code:

uint32_t cnt = 5;
int32_t valueInt = -100000;
int32_t resultInt = valueInt / cnt;

expected -20000
computed 858973459

Compilant Code:

int32_t resultInt = valueInt / static_cast<int32_t>(cnt);

This is a critical bug because it works fine as long valueInt is positive.
It would be helpful if this rule would be added.


Hello @Inok,
Thank you for the suggestion. Indeed, it looks like a nasty bug and should be detected if we manage to find an acceptable heuristic to avoid too many false positives. We do have this idea in our backlog: CPP-205. I have recorded your interest in the ticket.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.