HH said:
int main()
{
uint x = -1;
int y = -1;
if (x == y)
printf("EQUAL");
else
printf("NOT EQUAL");
}
This code prints "EQUAL".
Well, no: This code doesn't compile, because `uint'
has not been declared. (There are other problems, too,
but that's not the point.) I'll answer on the assumption
that `uint' is a typedef'ed or #define'd alias for
`unsigned int'.
Does this mean that bit comparison is done for the
equality test? If it doesn't can you give me an example that shows bit
comparison isn't done?
No and no. C's comparison operators are all defined
as working with the values of their operands, not the
representations thereof. What you have discovered is
that (1) when an `unsigned int' and an `int' are compared,
the `int' value is first converted to `unsigned int', and
(2) `(unsigned int)-1 == (unsigned int)-1'.
I also wanted to know if we can assign a number to
uint & int variables such that "unit var != int var". Thanks so much
Assuming that `unit' is also an alias for `unsigned
int', it is possible for this to happen -- but only under
a rather "exotic" set of conditions. These conditions are
permitted by the C language Standard, but never ("What,
never?" "Well, hardly ever.") seen in practice:
1) The number must be in the allowable range for an
`unsigned int' but out of range for an `int', that
is, `INT_MAX < number && number <= UINT_MAX'.
2) The attempt to convert this too-large value to an
`int' produces an implementation-defined result
instead of raising an implementation-defined signal.
3) The implementation-defined result is a valid `int'
value with the interesting property that converting
it to `unsigned int' does not yield the original
number.
This chain of events is unlikely, but permitted by the
Standard -- converting a value from `unsigned int' to `int'
and back again is required to be the identity operation only
if the value is in the legitimate range of an `int'. If it's
not, the Standard permits other things to happen. It's more
a theoretical possibility than anything else, though.
Here's the big question: Why do you care? What are you
trying to do?