Is there any reason to prefer static_cast<>
over C style casting? Are they equivalent? Is there any sort of speed difference?
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.
static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.
The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.
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.
In short:
static_cast<>()
gives you a compile time checking ability, C-Style cast doesn't.static_cast<>()
is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With