Yes I know you shouldn't use C style casts in C++, but in some cases I really think it's a lot more readable if you do, compare these two for example:
d = ((double)i * 23.54) / (d + (double)j);
d = (static_cast<double>(i) * 23.54) / (d + static_cast<double>(j));
Which one is more readable?
Now on to my main question. Obviously I prefer the upper one, but there is one way to make it even more readable in my opinion:
d = (double(i) * 23.54) / (d + double(j));
My question here is, will this be less efficient? Will the compiler create more doubles in this case than if they were casted with the other methods, or is it clever enough not to? Is this more or less bad than typical C-style casts?
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
Static casts are only available in C++.
In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.
They're all unreadable. You should write:
d = (i * 23.54) / (d + j);
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