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

Jameson Nash via llvm-dev llvm-dev at lists.llvm.org
Thu Jun 13 10:17:29 PDT 2019

> Should `a + (b - c)` be the same as `(a + b) - c`? You either need a
signed type or wrapping to have reasonable answers here

Depending on what "reasonable" means here, only wrapping (unsigned in C)
gets you this commutative property. For a signed value with C, it's
possible for one of these to be undefined behavior, while the other returns
a reasonable value. For instance, `a == b == c == std::
is probably unusual as a value, but could be used as a sentinel (perhaps to
represent an infinite or empty set). Of course, the unsigned result might
just be nonsense.

Anyways, I don't have a strong opinion either way, since I think they both
can have surprises.

One other occasional benefit to using unsigned that can be surprising is
that power-of-two division is slightly cheaper (since it doesn't need to
handle negative numbers):

(ssize_t)x / 2
shrq $63, %rax
leaq (%rax,%rdi), %rax
sarq %rax

(size_t)x / 2
shrq %rdi

> > is there any container

I'd posit that UINT_MAX is uncommon, but pretty easy to exceed (although it
needs a 64-bit machine to represent it). For example, anything that might
need to handle the return value of `MemoryBuffer::getFile` could come
across a file that's larger than 2GB.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20190613/ade1da77/attachment.html>

More information about the llvm-dev mailing list