Hacker News new | ask | show | jobs
by wat10000 29 days ago
Apparently signed integer overflow UB helps with loop optimizations because it makes it easy to prove the loop always terminates. I assume that's not why it's UB, though; surely it's UB because some systems trapped on overflow, or produced different results due to using 1's complement, and the optimization side of the rule was a happy accident. There's a lot of history in this language and it really shows.
1 comments

> Apparently signed integer overflow UB helps with loop optimizations because it makes it easy to prove the loop always terminates

I tried googling but couldn't find hard numbers on the performance impact of GCC's -fwrapv flag. As you'd imagine, it forces wrapping for overflowing arithmetic on signed integer types. [0]

I also have to wonder how instructive that would be anyway. The GCC devs presumably don't prioritise the performance impact of that flag. If the C language mandated it, they might find other ways to achieve similar optimisation.

This page [1] looks at the related flag for trap-on-signed-overflow, and found an impact of very roughly 6%.

See also: John Regehr's posts on this topic. [2][3] He dislikes Java's implicit wrap behaviour, as it's rarely what the programmer wants to happen. Java programmers almost never use the addExact method, [4] as it's so syntactically clumsy.

> surely it's UB because some systems trapped on overflow, or produced different results due to using 1's complement, and the optimization side of the rule was a happy accident

Per this StackOverflow answer [5] I think you have it right.

[0] https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html

[1] https://danluu.com/integer-overflow/

[2] https://blog.regehr.org/archives/1401

[3] https://blog.regehr.org/archives/1154

[4] https://docs.oracle.com/en/java/javase/25/docs/api/java.base...

[5] https://stackoverflow.com/a/18195756