views:

734

answers:

4

Is there any reason to prefer static_cast<> over C style casting? Are they equivalent? Is their any sort of speed difference?

+1  A: 

Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?

Doug T.
+16  A: 

C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime

also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts

Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.

When writing C++ I'd pretty much always use the C++ ones over the the C style.

Glen
definitely the best benefit, +1 :)
Doug T.
+5  A: 

See A comparison of the C++ casting operators.

However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.

Furthermore, it can be difficult to find a specific type of cast in a large codebase.

the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.

eed3si9n
+3  A: 

See the excellent answers provided for this: different types of casts in C++

Ponting