I see some code in c like this
int main()
{
int x = 4, y = 6;
long z = (long) x + y;
}
what is the benefit of casting even though in this case it implicit? Which operation comes first x + y or casting x first?
In this case the cast can serve a purpose. If you wrote
int x = 4, y = 6;
long z = x + y;
the addition would be performed on int
values, and then, afterwards, the sum would be converted to long
. So the addition might overflow. In this case, casting one operand causes the addition to be performed using long
values, lessening the chance of overflow.
(Obviously in the case of 4
and 6
it's not going to overflow anyway.)
In answer to your second question, when you write
long z = (long)x + y;
the cast is definitely applied first, and that's important. If, on the other hand, you wrote
long z = (long)(x + y);
the cast would be applied after the addition (and it would be too late, because the addition would have already been performed on ints).
Similarly, if you write
float f = x / y;
or even
float f = (float)(x / y);
the division will be performed on int
values, and will discard the remainder, and f
will end up containing 0. But if you write
float f = (float)x / y;
the division will be performed using floating-point, and f
will receive 0.666666.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With