3 ms·
> Always use signed unless you have a reason not to. Even if a value can't naturally be negative, use signed. Can you elaborate on what benefits this approach
by WaffleIronMaker 4y ago
> Always use signed unless you have a reason not to. Even if a value can't naturally be negative, use signed.
Can you elaborate on what benefits this approach has? I would feel that, especially when a number cannot be negative, unsigned integers seem like a proper representation of the data?
- gugagore 4y agoHere is an example: https://wesmckinney.com/blog/avoid-unsigned-integers/ https://wesmckinney.com/blog/avoid-unsigned-integers/
- eru 4y agoA big problem is that C doesn't make you stick to the representation. If you accidentally subtract and go into 'negative' numbers, using an unsigned in C will just happily give you the wrong answer. Now in something like Haskell, it's much more robust advice to make invalid states unrepresentable. But C's compiler and runtime don't typically help you, when you are trying to break your representation.
- Quekid5 4y agoA couple of things I can think of off the top of my head: Since the compiler knows that certain things are UB using signed offers better (often significantly better) optimization opportunities then using unsigned. Plus, you get to use UBSan to detect bad code.