3 ms·
But using int doesn't wrap sooner or cause any errors at all, because it is automatically promoted to the native size due to this all being undefined behavior.
by saurik 2y ago
But using int doesn't wrap sooner or cause any errors at all, because it is automatically promoted to the native size due to this all being undefined behavior. Your example even directly demonstrates that, as the code had no chance of erroring in any way as it just returned the sum directly... the sum is even overflowing the int it is being stored into, that's how crazy the behavior of the code you wrote is.
And like, in addition to undermining your argument, that is also distressing, right? The code you wrote can be interpreted in a ton of different ways and the only reason the fast one makes any sense is if you squint hard enough so as to lose the details of the sizes and behaviors of all of the types that were declared... if you actually had to make the wrapping or errors you wish to see happen you'd have to have the slow code.
In contrast, the code using a native-sized unsigned type and != means only one thing, and that one thing is the fast code you said wanted to get... that makes it the correct code. It isn't optimized to that code due to undefined behavior: mathematically that lea multiplication is identical, and if you simulated all of the steps--including the wrap (and if we fixed the output type, the truncation)--you'd always get that result.
(And the reason I keep using the term "field" is because these types are elements of a modular finite field, and once you see them for what they are it becomes a lot easier to write correct code using them. There are even some modern languages where the native algebraic type is an element of a prime field, at which point confusing it for some kind of integer is extremely problematic.)
- uecker 2y agoLet's start with something simple: Those types are not fields but quotient rings. If you have learned enough math to understand this, please come back.