Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cast when the conversion is implicit?

Tags:

c

casting

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?

like image 668
TheCaptain Avatar asked Mar 07 '23 09:03

TheCaptain


1 Answers

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.

like image 114
Steve Summit Avatar answered Mar 10 '23 10:03

Steve Summit