user2419083
user2419083

Reputation: 94

Typecasting integers as doubles to get a double result from divison of the typecasted integers

I do not understand the underlying reason the output is a double between the following examples. In terms of:

Upvotes: 2

Views: 87

Answers (4)

dbush
dbush

Reputation: 225387

From the C standard, section 6.3.1.8: Usual arithmetic conversions:

First, if the corresponding real type of either operand is long double, the other operand is converted, without change of type domain, to a type whose corresponding real type is long double.

Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.

Otherwise, the integer promotions are performed on both operands.

So if one operand to an arithmetic operator is int and the other is double, the standard states that the resulting expression has type double.

Upvotes: 4

ryyker
ryyker

Reputation: 23236

For additional context of @dbush 's excellent answer, it is important to note that the standard specifies that for all arithmetic type conversions containing differing types, that conversion is from the smaller of two types to the largest:

Summarized from C11 - 6.3.1.8 Usual arithmetic conversions:

1st: if real type of either operand is long double, the other is converted to long double
2nd: Otherwise if real type of either operand is double, the other is converted to double
3rd: Otherwise if real type of either operand is float, the other is converted to float

And it goes on to specify how integer promotions are made in similar fashion...

Upvotes: 1

Magisch
Magisch

Reputation: 7352

Due to necessities in the evaluation, if one of the operands of a division is a double data type, the other is automatically promoted to that for means of calculation. In your example this happens because the operator precedence for an explicit cast is higher then for a divison.

If you want to only cast the result of the division, you can do:

d = (double)(a/b);

To ensure the integer division is performed first, and the explicit cast to double is performed second.

Upvotes: 1

Wicked
Wicked

Reputation: 126

The cast has precedence over the division, and an operation between a double and an int will produce a double

Upvotes: 1

Related Questions