[PATCH] D71607: Add unsigned subtraction warning, with suggestion to convert to unsigned literals.

Jeffrey Sorensen via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 17 06:42:14 PST 2019


sorenj created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Many C++ programmers are unaware that an expression of unsigned - signed will
promote the signed argument to unsigned, and the resulting underflow produces
a large positive rather than negative result. Hence the frequent errors
related to the test x.size() - 1 <= 0 when the container x is empty.

This clang tidy detects signed values being subtracted from unsigned values
and warns the user about the potential error. It is not perfect as it is
not always possible at compile time to reason about code when this comparison
is made.

The warning also suggests a fixit change that will append a "u" to numerical
constants - this makes the implicit cast explicit and signals that the
developer knew what they were doing in a subtraction. In other cases it
suggests the rather abhorrent static_cast<>().

The easiest fix is to not do subtraction at all, just move the operation
to the other side of the comparison where it becomes an addition - which
has none of these surprising properties.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D71607

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/UnsignedSubtractionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnsignedSubtractionCheck.h
  clang-tools-extra/test/clang-tidy/checkers/bugprone-unsigned-subtraction.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D71607.234289.patch
Type: text/x-patch
Size: 11862 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20191217/78bd29c9/attachment-0001.bin>


More information about the cfe-commits mailing list