What is the difference between static_cast<> and C style casting?


Question

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

1
182
7/3/2015 11:38:51 AM

Accepted Answer

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.

199
10/22/2009 6:52:04 PM

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 4-byte pointer ( a pointer to 4-byte datatype) 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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon