Reputation: 32776
I'm learning C++ coming from doing JavaScript professionally for years. I know the differences between signed
and unsigned
, but I'm not sure I understand why they even exist. Is it for performance or something?
Upvotes: 1
Views: 205
Reputation: 565
C is designed to be a high-level language but also able to do low-level stuffs easily, such as directly inserting assembly language code into the source code using the _ASM keyword. Assembly language works directly with the CPU registers and the arithmetic instructions work with both signed and unsigned integer. The variable type are probably designed in such way so that values can be transfer between CPU registers and variables without any conversion at all. C++ which extended from C also inherit this feature. After all, at that time when the C/C++ is invented, most of the programmers are also hardware engineers too.
Upvotes: 0
Reputation: 14117
They exist because the math to handle can differ.
Consider multiplying two 32 bit values to get a 64 bit value. Depending upon the sign of the operands, the upper 32 bits can differ between a signed multiply and an unsigned multiply. Getting down to assembly, this is why there is an IMUL and MUL instructions on the x86.
Upvotes: 0
Reputation: 35117
It comes in handy for low level situations where you need to describe length which obviously can't be negative. File sizes for example.
Upvotes: 2
Reputation: 208456
You can argue that with unsigned values you can obtain a larger positive range than with the equivalent signed types, but the main reason is that they allow mapping concepts in the domain where negative numbers make little or no sense. For example, the size of a container can never be negative. By using an unsigned type that becomes explicit in the type.
Then again, the existence of the two, and the implicit conversions pull a whole different set of problems...
Upvotes: 5
Reputation:
Because they're needed.
signed
types exist because sometimes one wants to use negative numbers.
unsigned
types exist because for some operations, e. g. bitwise logic and shifting, they're cleaner to use (e. g. you don't have to worry about how the sign bit is represented, etc.)
Upvotes: 5