standard type conversions

I read the following:

"C++ introduces a new casting operator called static_cast. A static cast works similarly to the C style cast, except it will only do standard type conversions, which reduces the potential for inadvertant misuse"

What is a standard type conversion? As far as I can tell, these two statements do the same thing:
C:
1
2
3
int nValue1 = 10;
int nValue2 = 4;
float fValue = float(nValue1) / nValue2;

C++:
1
2
3
int nValue1 = 10;
int nValue2 = 4;
float fValue = static_cast<float>(nValue1) / nValue2;


Why use static_cast when you can just use the C-style type conversion?
float(nValue1)

This isn't C, this is C++. A C equivalent would have been (float)nValue1

You are correct in that (in C++), float(nValue1), (float)nValue1, and static_cast<float>(nValue1) are the same.

When you use a C-style cast (or a function-style cast that you used, which is the same thing) in a C++ program, you're asking the compiler to try all of the following, in this order, and use the first one that can be compiled:
1. const_cast
2. static_cast (with some extensions, irrelevant here)
3. static_cast (with extensions) followed by const_cast
4. reinterpret_cast
5. reinterpret_cast followed by const_cast
the biggest problem is if you're casting between pointers and the compiler picks reinterpret_cast where you intended a static_cast. Also, C++ programs are usually trying to be const-correct and any surprise const_cast is unwelcome as well.
Last edited on
Safety. static_cast for instance does compile-time checks to make sure that a cast between two types can work. C-style casts don't and if they fail then they'll fail at runtime. Additionally, if you end up having casting issues, it's much easier to search through your code looking for a static_cast than a C-style cast. Finally, static_cast can only do, as you mentioned, standard casts. I'll quote from the tutorial as to what they are:

...the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions.
http://www.cplusplus.com/doc/tutorial/typecasting/

Does static_cast seem limiting? It is, but in being limiting, it's also precise. There are other C++-style casts that perform the conversions (and more) that the C-style cast can perform.

Generally speaking, C-style casts enable a wide range of casting, where C++-style casts are more specific and convey intent better. That's my two cents.

-Albatross
Topic archived. No new replies allowed.