In the following code segment what will be:
{ unsigned int x=-1;
unsigned int x=-1;
1
is an integer literal and has type int
(because it fits in an int
). Unary -
applied to an int
causes no further promotion so -1
is an int
with value -1
.
When converted to an unsigned int
modulo 2^N arithmetic is used where N is the number of value bits in an unsigned int
. x
has the value 2^N - 1 which is UINT_MAX
(What's MAX_UNIT
?).
int y;
y = ~0;
Again 0
is type int
, in C all the allowed representations of int
must have all the value bits of an int
representing 0 as 0. Again no promotion happens for unary ~
so ~0
is an int
with all value bits being 1. What it's value is is implementation dependent but it is negative (the sign bit will be set) so definitely neither of UINT_MAX
or INT_MAX
. This value is stored in y
unchanged.
if(x == y)
printf("same");
else
printf("not same");
In this comparison y
will be converted to unsigned int
in order to be compared with x
which is already an unsigned int
. As y
has an implementation value, the value after conversion to unsigned int
is still implementation defined (although the conversion itself is modulo 2^N and fully specified). The result of the comparison is still implementation defined.
So in conclusion:
implementation defined,
UINT_MAX
, implementation defined
In practice on ones' complement:
not same,
UINT_MAX
, -0 (aka 0)
sign plus magnitude:
not same,
UINT_MAX
,INT_MIN
two's complement:
same,
UINT_MAX
, -1