Did I miss something? I got to the end and still don't know what -n % n actually accomplishes in practice, nor why it's mainly used in high-performance code
First it's important to note that `n` is unsigned; if it's signed the value of `-n % n` is 0, intuitively.<p>For unsigned n, the value is: MAX - n + 1 (where max is the maximum representable value in the type of n, e.g., UINT_MAX). The article explains this nicely. (I thought of 2's complement when reasoning through this, but you don't actually need to assume 2's complement to follow the reasoning).<p>So, `-n % n` computes `(MAX - n + 1) % n` efficiently, without needing to worry about corner cases.<p>I suspect this is useful when you want to generate random numbers with a limited range, where the range doesn't cleanly divide UINT_MAX. You need to cut a bit off the top from your underlying random number generator.
<p><pre><code> let threshold = (0 &- range) % range
</code></pre>
> It is somewhat inconvenient that Swift forces us to write so much code, but we must admit that the result is probably less likely to confuse a good programmer.<p>Oh come on, it's basically just one extra character.
> <i>warning C4146: unary minus operator applied to unsigned type, result still unsigned</i><p><pre><code> #ifdef _MSVC
x = ~x + 1; // "Manual" two's complement to avoid warning.
#else
x = -x; // Regular two's complement any good C coder knows
#endif</code></pre>
This only works on two's complement machines. The C++ standard only required two's complement with c++20.<p>That being said I am not sure I've ever programmed a one's complement machine.