Reputation: 161
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
?
Upvotes: 3
Views: 99
Reputation: 361879
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.
Upvotes: 5
Reputation: 224387
The typecast operator has higher precedence than the division operator. So this:
(double) sum / count
Parses as this:
((double) sum) / count
Meaning that sum
is typecast to a double
. Then, because one operand to /
has type double
and the other has type int
, The int
operand is converted to double
as per the usual arithmetic conversions and floating point division is performed.
Upvotes: 2