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 something
s are double
s.)
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.
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.
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.
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.
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.
Many of these static_cast
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With