Unsigned integer literal negative sign

Today I came across this strange behavior, can someone explain why this is happening?

var x = -1U; // When using -1UL it complains though.
Console.WriteLine(x.GetType().Name);
Console.WriteLine(x);

Output:

Int64

1

MSDN says:

If the literal suffix is ​​U or u, it has the first of these types in which its value can be represented: uint, ulong.

https://msdn.microsoft.com/en-us/library/aa664674%28v=vs.71%29.aspx

+4
source share
3 answers

, -1, U. - 1U. 1U uint, . uint a long.

+1

, unary operator - https://msdn.microsoft.com/en-us/library/aa691145(v=vs.71).aspx

T, T int long, . T, T. ulong.

-

   var x =-1UL; 

Operator '-' cannot be applied to operand of type 'ulong ,

,

 var x =2UL-1UL; 

, binary operator

var x=-1UL, var x=0UL-1UL, , succeded, -1UL, UL, 0 and 18446744073709551615, -1UL , . ushort.

+2

var, , -:

var x = -1U; // it is converted to simple -1

-1 , uint - long

Console.WriteLine(x.GetType().Name);  // displays long (Int64)
Console.WriteLine(x);                 // displays -1

As said, you can use the keyword uncheckedso that the compilation knows that it should not perform an overflow check. Quote from MSDN :

Invalid keyword used to suppress overflow for integral types of arithmetic operations and transforms.

So, this should compile and run, and x will be of type ulong:

// UInt64 here
    var x = unchecked((ulong)-1);
0
source

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


All Articles