tags:

views:

86

answers:

2

Consider following program:

static void Main (string[] args) {
    int i;
    uint ui;

    i = -1;
    Console.WriteLine (i == 0xFFFFFFFF ? "Matches" : "Doesn't match");

    i = -1;
    ui = (uint)i;
    Console.WriteLine (ui == 0xFFFFFFFF ? "Matches" : "Doesn't match");

    Console.ReadLine ();
}

The output of above program is:

Doesn't match
Matches

Why the first comparison fails when unchecked conversion of integer -1 to unsigned integer is 0xFFFFFFFF? (While the second one passes)

+1  A: 

In the second case you cast -1 into uint, getting 0xFFFFFFFF, so it matches as expected. In the first case apparently the comparison is done in a format with suitable range for both values, allowing for the mathematically correct result that they do not match.

Tronic
+5  A: 

Your first comparison will be based on longs ... since 0xFFFFFFFF is not an int value :)
Try to write

Console.WriteLine( (long)i == 0xFFFFFFFF ? "Matches" : "Doesn't match" );

and you will get a cast is redundant message

tanascius
No, 0xFFFFFFFF is a uint value... just try that : `0xFFFFFFFF.GetType().Name`
Thomas Levesque
@Thomas: ok, you are right. The point is: it's not in int ... edited
tanascius
There is a compiler warning on the i == 0xFFFFFFFF saying "Comparison to integral value is useless; the constant is outside the range of int". So what @tanascius said.
btlog
I don't receive any warning when I compile the program posted in question. My warning level is set to 4. Am I missing something? (Using VS 2008, .NET 3.5)
Hemant