Search code examples
c++ccastingreadability

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?


Solution

  • The compiler will "create" exactly the same number of doubles. There is no practical difference between casting to and constructing primitive numeric types.