Quentin Pope said:
no ! unsigned int, and signed int are very different the way they are
represented in bits.
They're not all that different. In fact, in the absence of padding bits
and/or trap representations, the language guarantees that a value that's
representable as int and unsigned int (i.e., in the range 0 .. INT_MAX)
has the same representation in both types.
therefore, when you to compare the 2 different types
(like comparing apples and oranges) one of them has to be converted, in
this
case, the 'int' is converted to a 'uint', and becomes 0, since unsigned
numbers cannot be less then zero.
It's true that one of them is converted. This is because the language
standard says so; it's not a consequence of their representations. The
language *could* have defined "==" as a bitwise comparison (and in fact
that would have yielded the same results for int vs. unsigned int
comparisonms on 2's-complement systems).
But you're mistaken about the semantics of the conversion. When an
integer value is converted to an unsigned type, and the value cannot be
represented in the target type, " the value is converted by repeatedly
adding or subtracting one more than the maximum value that can be
represented in the new type until the value is in the range of the new
type" (C99 6.3.1.3p2). In this particular case, convering the int value
-1 to unsigned int yields UINT_MAX.
and besides, the == operator it *not* a bit comparison operator, it is a
variable comparison operator, if you want to do bit comparison you use the
bitwise operators, &,|,^,~. (and, or, exclusive or, not. respectively)
It's more accurate to say that it's a *value* comparison operator; there
needn't be any variables involved (consider "1 + 1 == 2").
The bitwise operators don't do comparisons. If you want to do
a bitwise equality comparison, the memcmp() function is probably
the best approach. Or you could treat the objects as arrays of
unsigned char and compare the element values (that's basically what
memcmp() does).
yes, if unit var = 1, and int var is any value other than 1 (-1, 0, -10,
10,
100, whatever) then they will be 'not equal' if you use the operator '!='
for example:
uint x = 1;
int y = -1;
if (x == y)
printf("EQUAL");
else
printf("NOT EQUAL");
will print NOT EQUAL since y is converted to an unsigned int and becomes
0
No, it will print NOT EQUAL because y is converted to an unsigned int
and becomes UINT_MAX (typically 4294967295), which is not equal to 1.
You'd get the same result if "==" did a bitwise comparison.