Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I assign a negative value to an unsigned variable?

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?

like image 980
ckv Avatar asked Apr 26 '10 06:04

ckv


People also ask

What happens when you cast a negative number to an unsigned int?

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.

Can signed ints be negative?

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).

Can uint8_t be negative?

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...

Is unsigned integer always positive?

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).


2 Answers

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.

like image 162
Dennis Zickefoose Avatar answered Sep 26 '22 11:09

Dennis Zickefoose


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

like image 28
Jasmeet Avatar answered Sep 22 '22 11:09

Jasmeet