1

If I write this function:

void f(unsigned int i) { .. }

and then call it like this:

int main() { f(-1); }

it is allowed by the standard, but it is most probably a risky bug that can cause, for example, a very long runtime (if f tries to loop from i down to 0, for example). However, both clang++ (with std=c++20) and clang-tidy (with checks=*) do not generate any warnings for this code. I find it strange, since they give warnings on much less dangerous issues, such as using "magic numbers" in the code, not using curly braces in an "if" statement, and even putting include statements in a non-standard order.

Is there any reason that passing a negative number as an unsigned int is not considered bug-prone and worthy of warnings by these tools?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • It's perfectly valid and well-defined behavior to underflow an unsigned value. It will simply add `UINT_MAX + 1` to the value until it is in the range of values represented by `unsigned int`. – Christian Gibbons Mar 13 '21 at 17:37
  • @ChristianGibbons I know that. But it is also perfectly valid and well-defined to e.g. use "magic numbers" in the code, and still clang-tidy warns against it. There are many other valid and well-defined statements that generate compiler warnings. – Erel Segal-Halevi Mar 13 '21 at 21:02
  • I would posit that it is fairly standard practice to convert signed values to unsigned in order to perform bit-wise operations, and programmers would find it rather obnoxious to receive warnings for perfectly good and sane code. If you really want a warning for it, you can always build with `-Wsign-conversion`. – Christian Gibbons Mar 13 '21 at 21:36
  • @ChristianGibbons `-Wsign-conversion` seems like a good solution for me, thanks. – Erel Segal-Halevi Mar 14 '21 at 06:33

0 Answers0