Hacker News new | ask | show | jobs
by int_19h 630 days ago
One can reasonably argue that the only reason why people expect wraparound is because it was the default in C, not because it actually makes sense. If the code actually depends on wraparound to produce the correct result, making that explicit in the operators, as Zig does, is surely a better choice, not the least because it gives people reading the code a clear indication that they should be paying attention to that. OTOH most code out there in the wild treats it more as a "never gonna happen" situation and doesn't deal with it at all, which isn't really made any worse with full-fledged UB.
1 comments

Integer wrapping on overflow is not just a C thing, it happens at the hardware level as part of ALU instructions. It's actually kind of difficult to come up with a different behaviour that makes sense. Saturating arithmetic requires additional transistors.
It happens on hardware level for a single opcode, sure, but a 1:1 mapping between such an opcode and arithmetic operators in a high-level PL isn't a given, especially in presence of advanced optimizations.

In any case, PLs don't have to blindly follow what the hardware does as the default. Many early PLs did checked arithmetic by default. Conversely, many instruction sets from that era have specific opcodes to facilitate overflow checking.

The reason why we got it in C specifically is because of its "high-level PDP assembly" origins.