Kusavil
Kusavil

Reputation: 295

Casting double to int: how it really works?

Let's look at this program:

#include <iostream>

...

int main()
{
    double koza = ( 1+2, 54 + 6, foo(), bar(), (double) 8/9 );
    std::cout << koza << std::endl;

    return 0;
}

The output will be 8/9, which is 0.888889. If I had used static_cast<double> (8/9) or double(8/9) instead, then 8/9 would be calculated firstly, which would be interpreted as integer (so 8/9 equals 0), then I would have casting it on double, which would give me 0 as an output.

But how exactly (double) 8/9 works? Does it cast both 8 and 9 on double and then calculate that? Or it consider all that is after (double) as a double instead default int? Or in other way?

In classes, when we were in such a situation, wrote number as floating point numbers by adding .0 to integer, for example :

double x = 8.0.

But how will it would work here? Or I should ask: how exactly this works? Is there any difference between these three expressions below?

a) double x = 8.0 / 9;

b) double x = 8 / 9.0;

c) double x = 8.0 / 9.0;

Upvotes: 1

Views: 275

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275966

(double)8/9 is ((double)8)/9 - the (double) binds tightly.

When you operate on a double and an int with / the int is implicitly converted to a double.

The same is true of (most? all?) other binary operators that apply.

Upvotes: 4

Related Questions