|
|
|
|
|
by AndyKelley
2610 days ago
|
|
I think we just need a terminology update: https://github.com/ziglang/zig/issues/2402 Would you feel better if it was called "illegal behavior"? In the safe build modes of Zig, integer arithmetic, shifting, wrong union field access, etc is 100% well-defined. Integer overflow is defined to panic. Unless of course you use one of the wrapping arithmetic operators; in these cases it is defined to do wrapping arithmetic. Integer overflow is usually a bug. If it weren't illegal behavior, zig wouldn't be able to help you catch the bug. That's why clang's integer arithmetic sanitizer only works for signed ints. It's much better for programmers to specify their intent precisely, which is why Zig has different operators for wraparound and assert-it-doesnt-overflow. Undefined behavior in the unsafe modes is what lets the optimizer make code go fast. C has given undefined behavior a bad reputation, but it's a tool. Zig lets you decide exactly where to opt in or out of the speed/safety tradeoffs. |
|
I'm not immediately seeing how non-wrapping arithmetic can enable significant optimisation. What could be faster than an integer add? If you have an example, I would be very interested (the classic "infinite loop" example is not particularly meaningful in my view).
I always assumed that C left this undefined mostly to support non-two's complement machines, which should probably not be a concern anymore. That's the only explanation I can come up with that explains why unsigned arithmetic is well-defined, but not signed arithmetic.