4 ms·
> If you do not need arithmetic behavior, do not use signed integer, use unsigned. Because computer does not understand sign, so if you do not need a sign, do n
by tredre3 4y ago
> If you do not need arithmetic behavior, do not use signed integer, use unsigned. Because computer does not understand sign, so if you do not need a sign, do not use it.
That's interesting. In my career (embedded development) I've learned to do the opposite. Always use signed unless you have a reason not to. Even if a value can't naturally be negative, use signed. Use unsigned only if you need the extra bit, or if you're doing bitwise operations.
> Because computer does not understand sign
Computers understand signs just fine, we're long past the days of the 6502 N-flag being a glorified bit 7 check. All CPUs have signed instructions.
- 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.
- up2isomorphism 4y ago> That's interesting. In my career (embedded development) I've learned to do the opposite. Always use signed unless you have a reason not to. Even if a value can't naturally be negative, use signed. Use unsigned only if you need the extra bit, or if you're doing bitwise operations. In this case, since you make sure that the extra size gained by unsigned is not important to you all, then you can also go with signed by default. Basically it is the tradeoff between 1. robust in majority of the use cases 2. capability to do signed arithmetic 3. additional positive integer range. As long as you make a consistent selection and be mindful when you are in the danger zone, it can be handled.