Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 446
John Avatar asked Mar 23 '11 22:03

John


People also ask

What happens when static_cast fails?

As we learnt in the generic types example, static_cast<> will fail if you try to cast an object to another unrelated class, while reinterpret_cast<> will always succeed by "cheating" the compiler to believe that the object is really that unrelated class.

What is the point of static_cast?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What happens when you perform a static_cast?

C-style casts also ignore access control when performing a static_cast , which means that they have the ability to perform an operation that no other cast can.

Why do we use static_cast in C++?

In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.


1 Answers

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.

like image 91
Paul Z Avatar answered Sep 22 '22 04:09

Paul Z