3 ms·
Arithmetic mod the word size is quite useful, but it's useful to specialized code-- hashes, checksums, periodic counters, fast division by constants, implementa
by nullc 3y ago
Arithmetic mod the word size is quite useful, but it's useful to specialized code-- hashes, checksums, periodic counters, fast division by constants, implementations of fast algebraic codes for things like combinatorial number (en/de)coding.
For the counters, since you questioned it-- say you want your program to perform a calibration cycle every once in a while, the exact interval isn't critical. Just free run an unsigned iteration counter and then test that some masked version of it equals a constant.
All that said, when you want wrapping behavior you know it. It's critical that it's available, first class supported, and fast-- but it wouldn't hurt if you had to ask for it.
But the alternatives to wrapping aren't themselves magic bullets: Say you use saturating arithmetic, now lots of code that might have worked more or less fine with wrapping (or only been a little glitchy) goes into a hard lockup, esp since saturation breaks the property that var+1 != var, or fails in some more serious way, when e.g. because var+pos-pos != var.
And the wrapping behavior at least has the property that its fast on extant hardware, while implementing saturating or trapping operations is inherently slower.
Wrapping also manages to produce correct results by accident pretty often, like in my above point about var+pos-pos=var. Sometimes machine generated code does some nonsense that takes a variable out of range then pulls it back. Switching to saturating would just switch the cases that are magically correct, switching to trapping would turn any otherwise magically correct cases into failures. In some cases you might prefer a clean crash to potentially glitchy behavior, but in other cases there is no such thing as a "clean crash" and crashing on overflow is the worst failure possible (so whatever else might happen if it kept running could be no worse).
There is, unfortunately, no replacement for thoroughly understanding the behavior of a piece of code nor any replacement for formal analysis.
We shouldn't cry too much. Software is absurdly cheap to make compared to e.g. engineering and machining a part out of metal. But part of that ease is an illusion because it's only that easy if you don't care if the software is correct, and only need it to be somewhat correct or only correct some of the time.
Few of the drivers for improved software quality are actually backed by research either. Would doing X or Y instead be better? We don't know. Alternatives start with at least a minor headwind that there is a lot of experience out there dealing with the way things have historically been done. Unfortunately researching the interaction between programming languages and programmers is itself really hard.