0
long x = <some value>
int y = <some value>

I want to subtract y from x , which of the following will give me different or same results

 x = (int)x - y;

 x = x-y

 x = short(x) - short(y)

1 Answers1

0

The type long is "bigger" than int. Smaller types can be automatically casted to bigger types. So, this code:

someLongNumber + someIntNumber

is basically equal to

someLongNumber + (long)someIntNumber

So the output will be long. You don't have to cast if you want to place the result in x. However, if you want to place it in y, you must cast the x operand to int ((int)x), or the whole operation ((int)(x - y)).

CoderCharmander
  • 1,862
  • 10
  • 18
  • 1
    Nitpick: the Standard guarantees that a `long` has greater _rank_ than an `int`, but both may be the same size (the only guarantee is that a `long` is at least as wide as an `int`), and on 32 bit Windows platforms `long` and `int` are in fact the same size. Also, what you are calling an "automatic cast" isn't really a cast, but is referred to in the Standard as an _implicit conversion_. – ad absurdum Dec 16 '19 at 07:33
  • Please, consider adding a note about the possible overflows. – Bob__ Dec 16 '19 at 10:39