Hacker News new | ask | show | jobs
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.

2 comments

That sounds reasonable. I agree that overflow is often a bug (and in GCC can use -ftrapv to enforce that view). But overflow is also frequently what you want in algorithms that deal with counters or differences of sums. Maybe point out that there are well-defined operators available in Zig as well?

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.

Illegal behavior is a better name for a code sequence that is guaranteed to panic. There is too muchalready-established meaning around C and C++'s use of the phrase "undefined behavior"