I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables?
The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values.
A numeric variable is signed if it can represent both positive and negative numbers, and unsigned if it can only represent non-negative numbers (zero or positive numbers).
C and C++ are unusual amongst languages nowadays in making a distinction between signed and unsigned integers. An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.
A signed variable has to store its sign in some bit. Usually this is the most significant one, but it could be any of them. An unsigned variable has no sign bits; thus, the lowest value it can hold is 0. This means that for an unsigned variable a , the expression a >= 0 will always be true.
Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.
Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive and zero.
Unsigned and signed variables of the same type (such as int
and byte
) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.
For example, an unsigned byte
can represent values from 0
to 255
, while signed byte
can represent -128
to 127
.
Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With