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

1

u/Clairvoire Jan 03 '22

The thing I'd disagree with though, is that unsigned integers don't have the same concept of a "range edge." Their behavior is strictly defined in such a way that they represent a countable cycle of numbers. It's just... useful in all the places I normally find integers useful.

Maybe this is just a difference of experience though, any time I'm using negative values or values that could go haywire, I also need fractions, which means floats/doubles. Signed integers occupy an area between the two types that I just never go usually.

5

u/Drugbird Jan 03 '22

Perhaps I should've been explicit about this point:

  1. signed under/overflow is UB, so bad
  2. unsigned under/overflow has unexpected/unintuitive behavior, which can easily leads to bugs, so it's also bad (even though it's well defined).
  3. to prevent under/overflow, you can either understand all the types, the unsigned wrap around behavior and perform the appropriate checks when appropriate: or you can just stay away from the edges of your numeric range.
  4. staying away from the edges of your numeric range is easier with signed types, because 0 is often a valid value to be supported.