a still has a negative value! Why?Code:int a= INT_MIN;
a = -a;
printf("%d", a);
It also mentions an overflow... how come?
Printable View
a still has a negative value! Why?Code:int a= INT_MIN;
a = -a;
printf("%d", a);
It also mentions an overflow... how come?
Check the value of INT_MAX. Chances are you are dealing with a two's complement representation, so -INT_MIN cannot be stored in an int.
Let me explain it with a 16bit arithmetic. The value of INT_MIN for it will be -32768 and INT_MAX will be 32767. Thus when you negate INT_MIN you get 32768 but this can't be represented in it coz the maximum value of INT is 32767, thus it'll go to the other side and print the corresponding value which in this case is -32768(the same as INT_MIN). Would it had been 32769 it would have printed -32767 and so on.
Whats a two's complement representation?
Yes i can print INT_MIN value. If i try printing -(INT_MIN) it's same as INT_MIN instead of being positive.
For 2's complement, look here.
In 2's-complement, INT_MIN == -INT_MAX-1. For instance, if INT_MIN is -128, then INT_MAX is 127. So the negative of INT_MIN is 128, which is out of range.
Which of course is really just pure luck, because the behavior is undefined, since you are talking about signed values. It is not portable behavior.
Quzah.
Sure, I'm just being pedantic.
Quzah.