Why are there assignment operators (& =, + =), but without assignment operators (&, +) for short primitives?

I came across the fact that bitwise or arithmetic operations are not allowed for primitive types less than 32 bits in size, but the corresponding assignment operations are actually allowed:

short BitwiseAnd(short a, short b) { return a & b; }         // error
short BitwiseAndAssignment(ref short a, short b) { a &= b; } // works

short Add(short a, short b) { return a + b; }                // error
short AddAssignment(ref short a, short b) { a += b; }        // works

The same behavior holds for other short primitive types, such as byte, sbyteand ushort.

I understand that arithmetic and logical operations are defined for 32-bit and larger types ( int, long...), because this is what the processor provides ( see this question ), and the shorter types are extended and can be dropped by 8 or 16 bits. However, is there a reason why this will work in an assignment statement? At first I assumed that behind the scenes it is shortthrown at int, but then you will have an assignment / return value short value = (some int)that should give an error, since the cast is not implicit.

In another note: I tried the code in the direct Visual Studio window, but much more code works there. The direct window probably does some implicit casting that would normally be explicit. For example, short a = (int)5;allowed in the direct window. In order not to help.

+4
source share
2 answers

However, is there a reason why this will work in an assignment statement?

Yes: because otherwise the assignment operator could never work for these types - there was no syntax that would allow it to work. Pending a += bor a &= bclear, so the conversion is done automatically.

a + b a & b, : ; , , (short)(a+b) ..

+1

int, .

a & b, a b - short s, int, &, int, return int short . . (short)(a & b).

short BitwiseAnd(short a, short b) { return (short)(a & b); }  //no error!

short BitwiseAndAssignment(ref short a, short b) { a &= b; }

, (+=, *=,...) , int.


?

short a = 1;
short b = 2;

short c = a + b; //error! 

? + short. short int, , int . a b int , , int. int, short, .

short c = (short)(a + b)//this will work
+2

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


All Articles