John
John

Reputation: 16007

Why go through the trouble of static_cast-ing a number to a double?

Ran across this in code I'm working through:

double part2 = static_cast<double>(2) * somthing1
  * ( static_cast<double>(1) + something2 )
  + ( static_cast<double>(1) / static_cast<double>(2) ) * something3
  + ( static_cast<double>(1) / static_cast<double>(2) ) * pow ( something4, 3 );

(The somethings are doubles.)

I suspect that there's a really good reason for going through the trouble of doing

static_cast<double>(1)

and the like, but it seems like I could get by with a lot less typing.

What am I not understanding?

Thanks in advance.

Upvotes: 6

Views: 1401

Answers (3)

Alexandre C.
Alexandre C.

Reputation: 56956

This is equivalent to the much more readable

double part2 = 2 * somthing1 * (1 + something2)
  + 0.5 * something3 + 0.5 * something4 * something4 * something4

since integers are promoted to doubles each time an arithmetic operation has one double operand. The 0.5 double litteral is enough to promote everything to double.

Upvotes: 1

Paul Z
Paul Z

Reputation: 872

Many of these static_casts are unnecessary, because of automatic numeric promotion. The ones that are extremely necessary are the ones used on constructing the number 1/2, although in this case there's no obvious reason not to just say 0.5 instead. In any case a compiler that's paying attention will remove all of these and replace them with compile-time constants.

Upvotes: 7

Lindydancer
Lindydancer

Reputation: 26094

I agree with the previous answer that 2.0 would be much better here.

However, I found another red flag in the code, namely pow(something, 3). The pow function is designed to take two arbitrary values, x and y and return x^y. As this function must handle arbitrary values, it will do an approximation. However, this 1) is complex to calculate and 2) sometimes miss the mark. In this case, you would be much better of simply using something4 * something4 * something4.

Upvotes: 2

Related Questions