Index: llvm/docs/CodingStandards.rst =================================================================== --- llvm/docs/CodingStandards.rst +++ llvm/docs/CodingStandards.rst @@ -1534,6 +1534,31 @@ } }; +Prefer `int` for regular arithmetic +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Prefer `int` when possible and use `unsigned` only for bitmask and when you +intend to rely on wrapping behavior. + +It is rare that overflowing (and wrapping) an unsigned integer won't trigger +a program bug when the overflow was not intentionally handled. Using signed +arithmetic means that you can actually trap on over/underflow and catch these +bugs (when using fuzzing for instance). + +Unsigned integer also have a discontinuity right to the left of zero. Suppose +A, B and C are small positive integers close to zero, say all less than a +hundred or so. Then given `A + B > C` and knowing elementary school algebra, +one can rewrite that as `A > B - C`. But C might be greater than B, and the +subtraction would produce some huge number. This happens even when working +with seemingly harmless numbers like A=2, B=3, and C=2. + +For more information, see [unsigned: A Guideline for Better +Code](https://www.youtube.com/watch?v=wvtFGa6XJDU) and [Garbage In, Garbage +Out: Arguing about Undefined Behavior...](https://www.youtube.com/watch?v=yG1OZ69H_-o). +This panel discussion may also be helpful: +- https://www.youtube.com/watch?v=Puio5dly9N8#t=12m12s +- https://www.youtube.com/watch?v=Puio5dly9N8#t=42m40s + Microscopic Details -------------------