-5

why i can't make operators on 8- and 16-Bit Integrals

short x = 1, y = 1;
short z = x + y; // Compile-time error
Sayse
  • 42,633
  • 14
  • 77
  • 146
Nour Ahmed
  • 89
  • 6

2 Answers2

1

The explanation is given here.

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

Since there is no implicit conversion from int to short, you have to do

short z = (short) (x + y);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

You could if you cast the result, the point is: shorts are 16 bits number, hence a short can have a value between -32.768 and 32.767, but when you do short x = 5; you are actually assigning an integer as literal

Adding 2 integers can for sure overflow the shorts capacity, hence the complains of the ide...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97