C++: Add another 'good' example for cpp/unsigned-difference-expression-compared-zero.

This commit is contained in:
Geoffrey White
2024-07-04 16:43:09 +01:00
parent 7abece46c7
commit 1343e4c9aa

View File

@@ -1,10 +1,14 @@
unsigned limit = get_limit();
unsigned total = 0;
uint32_t limit = get_limit();
uint32_t total = 0;
while (limit - total > 0) { // BAD: if `total` is greater than `limit` this will underflow and continue executing the loop.
total += get_data();
}
while (total < limit) { // GOOD: never underflows.
while (total < limit) { // GOOD: never underflows here because there is no arithmetic.
total += get_data();
}
while ((int64_t)limit - total > 0) { // GOOD: never underflows here because the result always fits in an `int64_t`.
total += get_data();
}