5

Im preparing for a very tricky c# exam and this question popped up while doing so. I have the following code:

 uint zzz = -12u;

-12u is recognized as System.Uint32 literal but it can only be stored in variable of type long. Why is that ?

Phil Gan
  • 2,813
  • 2
  • 29
  • 38
Chris Nickson
  • 105
  • 2
  • 3
  • 8
  • 5
    Do you know what the `u` stands for? – Mark Byers Dec 04 '12 at 15:08
  • 3
    I'm guessing because an unsigned int is supposed to be unsigned? – Phil Gan Dec 04 '12 at 15:08
  • 2
    Hint: "-12u is recognized as System.Uint32" is incorrect. It would be correct to say "12u is recognized as System.Uint32". – vcsjones Dec 04 '12 at 15:09
  • unsigned means that only non-negative values are allowed. -12 is simply not representable in an uint variable – Daniel Hilgarth Dec 04 '12 at 15:10
  • I know what the u stands for, Im trying some unlikely situations. U stands for unsigned, while -12 is obviously negative number. However the binary representation of -12, when converted to a uint decimal number can fit perfectly in uint. But for some reason I cant store that value in a variable of type uint. – Chris Nickson Dec 04 '12 at 15:14

2 Answers2

12

What it is doing is taking the unsigned int 12 and trying to convert it into a negative value (the -) which requires a conversion to a type that can handle negative numbers as an unsigned int cannot.

Because it is an unsigned int it has possible values outside the range of int, so conversion to a long is required.

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • 1
    Yup; if you look at the [integer literal spec](http://msdn.microsoft.com/en-us/library/aa664674.aspx) you can see that the minus sign isn't part of the literal, so it's creating a `uint` and then having to widen it to `long` when negating it. – Rawling Dec 04 '12 at 15:15
0

because u is for unsigned int
for handling -ve sign it converting it into Long data type
-12u is a signed int data type & for storing it in unsigned type it uses long data type

Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70