phaazon
phaazon

Reputation: 2002

What does a C cast really do?

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.

Upvotes: 11

Views: 5432

Answers (4)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77474

Pointers are pointers - casting a pointer is a noop.

It was a memory address before, it is a memory address afterwards.

It is essentially a statement "let's assume that this is a pointer to type x for future type checking".

So you might call this a reinterpret_cast in terms of C++, as it does not perform extra compile time type checking that e.g. dynamic_cast or a static_cast does.

I don't think C has equivalents of an dynamic_cast ("insert runtime type check here") or a static_cast ("perform extra compile time type checks here").

Note that for non-pointers things will behave slightly differently.

int b = 1;
double a = (double) b;

is not so much a cast, but an explicit type conversion.

Upvotes: 2

simonc
simonc

Reputation: 42175

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.

Upvotes: 7

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507055

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.

Upvotes: 7

devrobf
devrobf

Reputation: 7213

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.

Upvotes: 10

Related Questions