Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

division of short returns int c# (short/short=int ?!)

Tags:

c#

division

short

I'm trying the following:

short value1 = 4;
short value2 = 2;
short result = value1 / value2;

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

Is there no such thing as division for short?
Is there a reason why short/short returns an int or just because?
The reason I'm wondering, is because I can divide int's eventhough its limitations (cast back from float)

like image 848
julian bechtold Avatar asked Sep 16 '25 11:09

julian bechtold


1 Answers

You are absolutely right:

When you divide two int numbers (between -2147483648 and 2147483647), the result will mostly be between the same boundaries, so the division result should be int, which is correct.

When you divide two short numbers (between -32768 and 32767), the result will mostly be between the same boundaries, so the division result should be short, while it is int, so this is wrong.

Also the documentation is wrong: it mentions the integer division being an integer type, while it clearly is not just an integer type, but the integer type.

By the way: there is one ±fault in my explanation (hence the "mostly"):

(-32768) / (-1) is not within the short boundaries, but what the heck:
(-2147483648) / (-1) is also not within the int boundaries!

like image 84
Dominique Avatar answered Sep 18 '25 23:09

Dominique