[PATCH] D63049: Coding Standard: Prefer `int` for regular arithmetic

Mehdi AMINI via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Jun 8 10:17:58 PDT 2019


mehdi_amini created this revision.
Herald added a project: LLVM.

This is a proposal to standardize a preference to use signed integer when possible. See inline diff for more info.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63049

Files:
  llvm/docs/CodingStandards.rst


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=2, and C=3.
+
+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
 -------------------
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D63049.203698.patch
Type: text/x-patch
Size: 1554 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20190608/a0024a7c/attachment.bin>


More information about the llvm-commits mailing list