Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a C cast really do?

Tags:

c

types

casting

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.

like image 775
phaazon Avatar asked Dec 06 '12 14:12

phaazon


3 Answers

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.

like image 100
devrobf Avatar answered Sep 19 '22 18:09

devrobf


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.

like image 35
Johannes Schaub - litb Avatar answered Sep 17 '22 18:09

Johannes Schaub - litb


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.

like image 29
simonc Avatar answered Sep 20 '22 18:09

simonc