283

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

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
dicroce
  • 45,396
  • 28
  • 101
  • 140
  • 6
    Related: http://stackoverflow.com/questions/103512/in-c-why-use-static-castintx-instead-of-intx – Flow Apr 07 '13 at 17:24

7 Answers7

293

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.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Glen
  • 21,816
  • 3
  • 61
  • 76
  • 85
    The only casts that can fail at runtime are `dynamic_cast`s. – R. Martinho Fernandes Jul 27 '12 at 00:13
  • 16
    C++ reinterpret_cast(U) can fail at run time pretty much the same way C style casts can, and they are all quite different from how dynamic_cast(U) fails. – Christopher Smith Sep 20 '12 at 02:29
  • 30
    ­­­­­˗1 normal C cast `(int)something` can't fail - either you get cast to int or compiler error. – Tomáš Zato Nov 16 '15 at 12:34
  • @TomášZato However, a C-style cast to a pointer or floating-point number could produce a trap representation that causes undefined behavior. – Davislor Apr 08 '18 at 19:37
  • 7
    Can you elaborate why C++ casts be searched more easily than C casts? – Minh Tran Apr 16 '18 at 15:08
  • 9
    @MinhTran For C++ style you can search for the keyword "cast" thru out your source files. But want could you do with the c-style casts? – hzh May 31 '18 at 16:01
  • 6
    @huangzonghao You can search for "(int)" or "int(". All you need to know is the type that you're searching for, which should be included anyway to filter out results. But to be honest, I don't know why this is an important feature -- I can't remember the last time I really had to search for a cast. – John Phu Nguyen Jun 01 '18 at 00:41
  • @MinhTran I agree with you. I guess I never had a chance to search for those things -- The casts appear so less frequent in code that you could almost always remember where you actually casted a thing. But I think the logic here is that programmers always want to have more control over the code? So at least it make you feel better when you know you can easily find the hidden casts. – hzh Jun 01 '18 at 14:08
  • 4
    @JohnPhuNguyen you can get a lot of false positives this way. I.e. from function prototypes or function pointer definitions and etc. Also, it'd be impossible to find just "all casts" while you can find "all `reinterpret_cast`s" and analyze them. – Dan M. Jun 20 '18 at 16:59
  • 4
    I just went through this the other day, where I changed ALL C-style casts to C++ casts. That was a big pain finding all of the various possible variations of data types and whitespace inside and surrounding the parenthesis. A simple search-and-replace is not easy. – Remy Lebeau Mar 09 '20 at 15:30
  • 1
    @RemyLebeau Use an editor with regex search&replace and you won't have to worry about whitespaces anymore. – deLock Jul 27 '20 at 07:54
  • 2
    @deLock I was using a regex search at the time. It was still a huge PITA to do. And here I am, months later, still finding cases that I missed the first time around. – Remy Lebeau Jul 27 '20 at 14:45
  • 1
    C styles are checked by compiler, too. I think there is no difference between static_cast and c style casts. – eral Aug 28 '20 at 10:47
  • What are the "4 different C++ style casts"? – Patrick Jan 18 '21 at 14:47
  • https://riptutorial.com/cplusplus/example/19819/c-style-casting "It's better to use new c++ cast, because s more readable and can be spotted easily anywhere inside a C++ source code and errors will be detected in compile-time, instead in run-time. As this cast can result in unintended reinterpret_cast, it is often considered dangerous." – Ivan Caravanio Aug 18 '21 at 13:35
230

In short:

  1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
  2. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt.
  3. Intentions are conveyed much better using C++ casts.

More Explanation:

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a pointer to a 4-byte type, pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

You can also check this page on more explanation on C++ casts : Click Here

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Hossein
  • 24,202
  • 35
  • 119
  • 224
  • 33
    I think instead of "4-byte pointer" you meant "pointer to 4-byte datatype" – iheanyi Jul 23 '14 at 19:55
  • but it allows int q = static_cast(c); – TonyParker Feb 05 '19 at 11:28
  • 7
    @TonyParker That's because there's nothing wrong with that line. – Braden Best Aug 05 '19 at 21:32
  • @TonyParker in this case, it will have the same effect as an implicit conversion in `int q = c;`. The type of the initialized variable dominates and the initializer is converted to the that type. Hence, the `c` will be promoted to `int` and then this result will be used to initialize the `q`. – rawrex May 05 '22 at 06:10
17

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.

Community
  • 1
  • 1
Eugene Yokota
  • 94,654
  • 45
  • 215
  • 319
15
struct A {};
struct B : A {};
struct C {}; 

int main()
{
    A* a = new A;    

    int i = 10;

    a = (A*) (&i); // NO ERROR! FAIL!

    //a = static_cast<A*>(&i); ERROR! SMART!

    A* b = new B;

    B* b2 = static_cast<B*>(b); // NO ERROR! SMART!

    C* c = (C*)(b); // NO ERROR! FAIL!

    //C* c = static_cast<C*>(b); ERROR! SMART!
}
Rishi Khaneja
  • 159
  • 1
  • 2
  • 7
    Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Apr 16 '15 at 11:15
  • 1
    I think the answer shows that "static_casts" checks for type conversions to make sure they are along valid paths in the hierarchy graph. In this particular example, casting from A* to B* or B* to A* is allowed because A and B form a path in the hierarchical graph. C* is not on the path so static_cast will produce compile-time error. Sidenote: It may be worth noting that casting from A* to B* may result in NULL with a dynamic_cast at run time depending on the true underlying object. – nitroglycerine Aug 21 '17 at 20:10
12

A great post explaining different casts in C/C++, and what C-style cast really does: https://anteru.net/blog/2007/12/18/200/index.html

C-Style casting, using the (type)variable syntax. The worst ever invented. This tries to do the following casts, in this order: (see also C++ Standard, 5.4 expr.cast paragraph 5)

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_castfollowed by const_cast
Ying Xiong
  • 4,578
  • 8
  • 33
  • 69
5

static_cast checks at compile time that conversion is not between obviously incompatible types. Contrary to dynamic_cast, no check for types compatibility is done at run time. Also, static_cast conversion is not necessarily safe.

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int.

The user of static_cast must make sure that the conversion is safe.

The C-style cast does not perform any check, either at compile or at run time.

kiriloff
  • 25,609
  • 37
  • 148
  • 229
4

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.
  • 64,223
  • 27
  • 138
  • 202