5 ms·
This is good general advice. A key difference is whether the type is meant to be an index (counting) or for arithmetic. Indexing with unsigned integers certain
by ridiculous_fish 11y ago
This is good general advice.
A key difference is whether the type is meant to be an index (counting) or for arithmetic. Indexing with unsigned integers certainly has its pitfalls:
while (idx >= 0) { foo(arr[idx]); idx--; }
But this is outweighed by the enormous and under-appreciated dangers of signed arithmetic!
Try writing C functions add, subtract, multiply, and divide, that do anything on overflow except UB. It's trivial with unsigned, but wretched and horrible with signed types. And real software like PostgreSQL gets it wrong, with crashy consequences: http://kqueue.org/blog/2012/12/31/idiv-dos/#sql http://kqueue.org/blog/2012/12/31/idiv-dos/#sql
- revelation 11y agoWell, there are builtin functions that do this safely for signed integers. Of course that means you need to be aware which calculations are potentially dangerous, you need to know about signed integer overflow problems in the first place, etc. ..
- michaelhoffman 11y agoWhat functions are those?
- kevinnk 11y agoFor gcc see https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...
- jchomali 11y agoI totally agree.
- nly 11y ago> Try writing C functions add, subtract, multiply, and divide, that do anything on overflow except UB. For those curious... https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow https://www.securecoding.cert.org/confluence/display/c/INT32...