C # 0 (minus) uint = unsigned result?

public void Foo(double d){ // when called below, d == 2^32-1 ... } public void Bar(){ uint ui = 1; Foo( 0 - ui ); } 

I would expect both 0 and ui to be promoted to signed lengths.

True, with a 0 literal during compilation, you can find out that listing in uint is safe,

but I suppose it all seems wrong. At least a warning should be issued.

Thanks!

Is a language specification covering a semi-ambiguous case similar?

+4
source share
3 answers

This is an int that is executed for uint to execute an expression from 0 (which is implicitly interpreted by the compiler as uint ). Note that int - uint is an implicit conversion, hence no warning. There is nothing wrong with the code, except that uint not a CLS compiler. You can read why here . Additional Information About the CLS Compiler on MSDN

0
source

Why should everything be promoted to long ? The specification (section 7.8.5) lists four operators for integer subtraction:

  • int operator-(int x, int y);
  • uint operator-(uint x, uint y);
  • long operator-(long x, long y);
  • ulong operator-(ulong x, ulong y);

Given that the constant value 0 implicitly converted to uint , but the value uint ui implicitly converted to int , the second operator is selected in accordance with the steps for resolving overloading of binary operators described in section 7.3.4.

(Is it possible that you did not know about the implicit conversion of constant expressions from 0 to uint and that this was the confusing part? For more details see section 6.1.9 of the C # 4 specification.)

The next section 7.3.4 (which then refers to 7.3.5 and 7.5.3) is a little tortuous, but I believe that it is clearly defined and not at all ambiguous.

If this overflow that bothers you would expect this to not work either?

 int x = 10; int y = int.MaxValue - 5; int z = x + y; 

If not, what's the difference here?

+7
source

In the checked context, if the difference is outside the range of the result type, a System.OverflowException is thrown. In an uncontrolled context, overflow is not reported, and any significant high-order bits outside the range of the result type are discarded.

http://msdn.microsoft.com/en-us/library/aa691376(v=vs.71).aspx

Technically, follow these steps:

 double d = checked(0-ui); 

As a result, you will get a System.OverflowException , which you might expect, but according to the specification, since this is not checked, an overflow is not reported.

0
source

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


All Articles