I was curious to know what would happen if I assign a negative value to an unsigned variable.
The code will look somewhat like this.
unsigned int nVal = 0; nVal = -5;
It didn't give me any compiler error. When I ran the program the nVal
was assigned a strange value! Could it be that some 2's complement value gets assigned to nVal
?
An unsigned integer will never be a negative value, the smallest value it can be is 0 (zero). The values you get are not garbage. Assigning -1 to an unsigned type will give you the maximum value that variable can hold.
This attribute of being positive, negative, or zero is called the number's sign. By default, integers are signed, which means the number's sign is stored as part of the number (using a single bit called the sign bit). Therefore, a signed integer can hold both positive and negative numbers (and 0).
UInt8 is Unsigned Integer and it has range of 0... 255 so you cannot store value beyond this range means non negative and with in 255 , if you want to store negative value then use Int8 and its range is -128...
Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive).
For the official answer - Section 4.7 conv.integral
"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where
n
is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]
This essentially means that if the underlying architecture stores in a method that is not Two's Complement (like Signed Magnitude, or One's Complement), that the conversion to unsigned must behave as if it was Two's Complement.
It will assign the bit pattern representing -5 (in 2's complement) to the unsigned int. Which will be a large unsigned value. For 32 bit ints this will be 2^32 - 5 or 4294967291
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