[llvm-dev] [RFC] Coding Standards: "prefer `int` for regular arithmetic, use `unsigned` only for bitmask and when you intend to rely on wrapping behavior."

Andrew Kelley via llvm-dev llvm-dev at lists.llvm.org
Tue Jun 11 13:10:26 PDT 2019


On 6/11/19 3:59 PM, Zachary Turner via llvm-dev wrote:
> On Tue, Jun 11, 2019 at 12:24 PM Mehdi AMINI <joker.eph at gmail.com
> <mailto:joker.eph at gmail.com>> wrote:
> 
>     I agree that readability, maintainability, and ability to debug/find
>     issues are key. 
>     I haven't found myself in a situation where unsigned was helping my
>     readability: on the opposite actually I am always wondering where is
>     the expecting wrap-around behavior and that is one more thing I have
>     to keep in mind when I read code that manipulate unsigned. So YMMV
>     but using unsigned *increases* my mental load when reading code.
> 
> I'm on the other end.  I'm always reading the code wondering "is this
> going to warn?"  "Why could a container ever have a negative number of
> elements?"  "The maximum value representable by the return type
> (unsigned) is larger than that of the value i'm storing it in (signed),
> so an overflow could happen even if there were no error.  What then?"

This is why the Zig frontend has the arithmetic operators +,/,*,- assert
that overflow does not occur for *both* signed and unsigned integers.
The wrapping operators +%,/%,*%,-% are available when one needs a
guaranteed twos complement wraparound.

This gives the best of both worlds, where you can use proper types
matching the range of values, yet have the desired performance
optimizations (and sanitation checks) that only signed integers have in
C/C++.

In fact, in Zig, unsigned integers are actually more optimizable than
signed integers! https://godbolt.org/z/QICZyy

Andrew

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: OpenPGP digital signature
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20190611/92e63331/attachment.sig>


More information about the llvm-dev mailing list