Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C style casting and readability in C++

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?

like image 234
DaedalusAlpha Avatar asked Dec 09 '10 15:12

DaedalusAlpha


People also ask

What is a C-style cast?

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.

Can I use static_cast in C?

Static casts are only available in C++.

Why is static_cast better than C-style cast?

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.

What is Reinterpret_cast in C?

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.


1 Answers

They're all unreadable. You should write:

d = (i * 23.54) / (d + j);
like image 139
R.. GitHub STOP HELPING ICE Avatar answered Oct 11 '22 08:10

R.. GitHub STOP HELPING ICE