News for hackers. Stuff that matters.
Re:A Guide to Undefined Behavior in C and C++ (2010) by guimplen on Sunday March 16, 2025 @08:42PM (#43384032)
The first example (signed integer overflow) is no longer valid in newer standards of C. Now it should use the two-complement semantics and no UB.
Re:A Guide to Undefined Behavior in C and C++ (2010) by Rusky on Sunday March 16, 2025 @08:55PM (#43384109)
I believe they only standardized the two's-complement representation (so casts to unsigned have a more specific behavior, for example) but they did not make overflow defined.
Re:A Guide to Undefined Behavior in C and C++ (2010) by LegionMammal978 on Sunday March 16, 2025 @09:57PM (#43384481)
Yeah, signed integer overflow is as UB as ever. I've heard the primary reason for it is to avoid the possibility of wraparound on 'for (int i = 0; i < length; i++)' loops where the 'length' is bigger than an int. (Of course, the more straightforward option would be to use proper types like size_t for all your indices, but it's a classic tradition to use nothing but char and int, and people judge compilers based on existing code.)
Re:A Guide to Undefined Behavior in C and C++ (2010) by ForTheKidz on Monday March 17, 2025 @01:07AM (#43385366)
ptrdiff_t is also useful in this case if signed semantics are desired.
Re:A Guide to Undefined Behavior in C and C++ (2010) by vlovich123 on Monday March 17, 2025 @01:33AM (#43385460)
> I've heard the primary reason for it is to avoid the possibility of wraparound on

Making it UB doesn’t fix that in any way that I can think of.

Re:A Guide to Undefined Behavior in C and C++ (2010) by anttihaapala on Monday March 17, 2025 @02:41AM (#43385740)
What it means is that since i as the variable is monotonically increasing, an array indexing operation that is in the loop body can be replaced with an incrementing pointer instead, which eliminates quite a lot of code. An example here: https://pvs-studio.com/en/blog/posts/cpp/0374/
Re:A Guide to Undefined Behavior in C and C++ (2010) by pajko on Monday March 17, 2025 @07:46PM (#43394031)
UB can be converted to ID by using -fwrapv (to "standardize" the wrapround, which does not necessarily help if the overflow was not intentional) or -ftrapv (generate an exception).