Why is the comparison of int and uint not performed in one case, but not in another?

Consider the 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 the program above:

 Doesn't match Matches 

Why does the first comparison fail when the unchecked conversion of the integer -1 to an unsigned integer is 0xFFFFFFFF? (As long as the second passes)

+4
source share
2 answers

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 the message cast is redundant

+5
source

In the second case, you throw -1 at uint, getting 0xFFFFFFFF, so it matches what was expected. In the first case, apparently, the comparison is performed in a format with a suitable range for both values, which allows you to get a mathematically correct result that they do not match.

+1
source

Source: https://habr.com/ru/post/1303239/


All Articles