Hacker News new | ask | show | jobs
by porges 3993 days ago
The point here is not particularly about signedness, it's that UB allows better optimizations to be performed.

If overflow is defined to wrap around then it's potentially an infinite loop (take N == MAXVALUE). With overflow defined as UB you can say the loop executes exactly N times (because you're not allowed to write code that overflows).

So UB is both bad and a source of power :)

1 comments

> The point here is not particularly about signedness

But in the case of C, that is what it is about since unsigned integers have defined behavior, so you can only have UB and the optimizations when you use a signed integer.

Yes, but more generally UB allows optimizations that wouldn't be allowed otherwise. The whole reason C has so many undefined behaviors is for the benefit of compiler writers.
I believe it is not the original reason: most UB are about funky HW. For instance for the non-wrap signed int it can be explained because C does not assume you have 2-complement hardware.
More specifically, some early hardware would trap on signed overflow. A lot of undefined behavior in C actually comes from "some machine would cause a trap", and C predates the invention of precise trapping in out-of-order processors. The possibility of traps is generally the difference between undefined behavior or unspecified/implementation-defined behavior.