Search code examples
c++ccasting

What does a typecast at the beginning of an arithmetic expression apply to?


I don't understand how a typecast can sit at the beginning of a binary arithmetic expression. Does it typecast both variables or only one?

#include <stdio.h>
main()
{
    int sum = 17, count = 5;
    double mean = (double) sum / count;
    printf("Value of mean : %f\n", mean );
}

Is it casting (double) (sum / count) or only ((double) sum) / count?


Solution

  • It is parsed as ((double) sum) / count. Casting one of the operands is a common trick to force floating-point division. int / int would use integral division which truncates the decimal portion. double / int forces the second operand to be coerced into a double as well, resulting in double / double which doesn't truncate.

    Notice that if it were parsed as (double) (sum / count) it would not work. This would still perform integer division, truncate the decimal portion, and then cast that result to a double. The cast would come too late.

    When in doubt, consult cppreference.com. Their operator precedence chart shows that C-style casts have higher precedence than division:

    The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence.

    operator precedence chart