I write more and more C applications, and now I wonder something about casts. In C++, a dynamic cast is a very costly operation (for instance a down-cast), but I don’t even know for static one.
In C, I had to write something like that:
assert ( p ); /* p is void* */
int v = *(int*)p;
Is it a « C dynamic-cast »? Is it quite the same as the static_cast<int*>(p)
of C++? How much does it cost?
Thanks in advance.
A cast in C is only meaningful at compile time because it tells the compiler how you want to manipulate a piece of data. It does not change the actual value of the data. For example, (int*)p
tells the compiler to treat p
as a memory address to an integer. However this costs nothing at run time, the processor just deals with raw numbers the way they are given to it.
A C cast is more like all C++ style casts except dynamic_cast
combined. So when you cast an int to another integer type, it is static_cast
. When you cast pointers to other pointer types or to integer types or vice versa, it is reinterpret_cast
. If you cast away a const
, it is const_cast
.
C does not have something similar to dynamic_cast
since it has concept of types of objects and would have no use for them like C++ either (no virtual functions ...). Types with regard to interpreting an object's bits only become important when combined with expressions referring to objects, in C. The objects themselfs don't have types.
A C cast of a pointer is more like a C++ reinterpret_cast
. It instructs the compiler to treat a variable as being of a different type and costs nothing at runtime.
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