开发者

Why does the int and uint comparison fails in one case but not in another?

开发者 https://www.devze.com 2022-12-21 21:16 出处:网络
Consider following program: static void Main (string[] args) { int i; uint ui; i = -1; Console.WriteLine (i == 0xFFFFFFFF ? \"Matches\" : \"Doesn\'t match\");

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)


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消