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

ckv picture ckv · Apr 26, 2010 · Viewed 85k times · Source

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?

Answer

Dennis Zickefoose picture Dennis Zickefoose · Apr 26, 2010

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.