3 ms·
Unsigned overflow is defined but that doesn't necessarily make it any more expected when it happens. It can still ruin your day, and in fact it happens much mor
by modeless 11y ago
Unsigned overflow is defined but that doesn't necessarily make it any more expected when it happens. It can still ruin your day, and in fact it happens much more often than signed overflow, because it can happen with seemingly innocent subtraction of small values. After personally fixing several unsigned overflow bugs in the past few months I'm going to have to side with the Google style guide on this one.
- Peaker 11y agoIf you underflow an unsigned you get a huge value that's going to be invalid by any range check unless you assume entire unsigned range is available. But if you use signed, you have to check for values under zero AND the top of the range. So I don't understand how the bugs were caused by unsigned overflow. Wouldn't they still be bugs with negative results in signed numbers?
- modeless 11y agoMostly the errors are expecting that a calculation is using signed arithmetic when it's not, and getting a large positive value where you expected a small negative value. It's easy to forget the signedness of a variable, but the biggest problem is probably C's unfortunate tendency to silently convert signed to unsigned when at least one unsigned value is involved in a calculation. This causes unsigned arithmetic to contaminate parts of your code that you thought were signed.
- Peaker 11y agoI think I have a handful of negative numbers in hundreds of thousands of lines of C code. It's quite rare, IME. By the way, an underflowed/large unsigned number used when a signed number is expected in most contexts (e.g: when adding as an offset) will behave correctly. It will fail when you try to compare it using < or >. If you use enable gcc warnings (which you ought to for every conceivably useful warnings :-) ), that will be caught.