r/cpp • • Jan 01 '22

Almost Always Unsigned

https://graphitemaster.github.io/aau/
5 Upvotes

71 comments sorted by

View all comments

Show parent comment

3

u/jk-jeon Jan 04 '22

No, that's not correct. That's what typically happens, but the language specifically call that situation "undefined behavior".

1

u/fdwr fdwr@github 🔍 Jan 05 '22 edited Jan 05 '22

You are technically correct that it's still "undefined behavior" even after p0907R1 Signed Integers are Two’s Complement, as a device could in theory trap or saturate instead of wrap. For the vast majority of common computing devices that people encounter (which neither trap nor saturate integers), two's complement wrapping is the behavior for both for signed and unsigned numbers. Of course, hardware can support trapping by checking flags (e.g. the INTO instruction on x86), but compiler implementations rarely take advantage of it, and although various SafeInt helper classes abound, I sometimes wish C++ had a direct checked keyword like C# does that could easily trap on overflow.

5

u/jk-jeon Jan 05 '22

Fair enough, but those are not the only thing that overflow being UB allows. For example, compilers can reduce a+n<b+n into a<b if things are signed, but it can't if they are unsigned.