c

Can a int value added to a float value?


/**Program for internal typecasting of the compiler**/
#include<stdio.h>

int main(void)
{
    float b = 0;
    // The Second operand is a integer value which gets added to first operand 
    // which is of float type.  Will the second operand be typecasted to float?
    b = (float)15/2 + 15/2;   
    printf("b is %f\n",b);
    return 0;
}

OUTPUT : b is 14.500000


Solution

  • Yes, an integral value can be added to a float value.

    The basic math operations (+, -, *, /), when given an operand of type float and int, the int is converted to float first.

    So 15.0f + 2 will convert 2 to float (i.e. to 2.0f) and the result is 17.0f.

    In your expression (float)15/2 + 15/2, since / has higher precedence than +, the effect will the same as computing ((float)15/2) + (15/2).

    (float)15/2 explicitly converts 15 to float and therefore implicitly converts 2 to float, yielding the final result of division as 7.5f.

    However, 15/2 does an integer division, so produces the result 7 (there is no implicit conversion to float here).

    Since (float)15/2 has been computed as a float, the value 7 is then converted to float before addition. The result will therefore be 14.5f.

    Note: floating point types are also characterised by finite precision and rounding error that affects operations. I've ignored that in the above (and it is unlikely to have a notable effect with the particular example anyway).

    Note 2: Old versions of C (before the C89/90 standard) actually converted float operands to double in expressions (and therefore had to convert values of type double back to float, when storing the result in a variable of type float). Thankfully the C89/90 standard fixed that.