tags:

views:

378

answers:

6

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?

+1  A: 

It will show as a positive integer of value of max unsigned integer - 4 (value depends on computer architecture and compiler).

BTW
You can check this by writing a simple C++ "hello world" type program and see for yourself

Dror Helper
I wrote and checked it thats why i asked the question but i didnt know how the compiler arrived at that positive value. Thanks
ckv
+1  A: 

Yes, you're correct. The actual value assigned is something like all bits set except the third. -1 is all bits set (hex: oxFFFFFFFF), -2 is all bits except the first and so on. What you would see is probably the hex value 0xFFFFFFFB which in decimal corresponds to 4294967291.

Martin
Bit's have nothing to do with it, integer representation isn't specified.
GMan
Your answer is correct, stringent, to the point and something I would never use in class.
Martin
+2  A: 

You're right, the signed integer is stored in 2's complement form, and the unsigned integer is stored in the unsigned binary representation. C (and C++) doesn't distinguish between the two, so the value you end up with is simply the unsigned binary value of the 2's complement binary representation.

perimosocordiae
It may not be stored in 2's compliment.
GMan
+2  A: 

It will assign the bit pattern representing -5 (in 2's compliment) to the unsigned int. Which will be a large unsigned value. For 32 bit ints this will be 2^32 - 5 or 4294967291

Jasmeet
Bit's have nothing to do with it.
GMan
+6  A: 

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 2^n 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 ]

Dennis Zickefoose
+4  A: 

From §4.7/2:

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

It is defined mathematically.

The conversion is independent from implementation, doesn't have anything to do with bits, etc. The only time implementation comes into play is in the size and way integers are represented, which has no effect on the conversion.

GMan