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

Mehdi AMINI via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 10 23:23:17 PDT 2019


mehdi_amini updated this revision to Diff 203981.
mehdi_amini marked 2 inline comments as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63049/new/

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=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
 -------------------
 


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


More information about the llvm-commits mailing list