c cast in c++, compile time or run time?

Go To StackoverFlow.com

1

does any one know if, for example, I'm writing in c++ the following code:

int a;
void *ptr = &a;
ptr = (char *)ptr + 1; //<-- this is the interesting line;

Does the (char *) only tells the compiler how to address this variable?
Or does it actually add more calculations in run time?

Thanks.

2012-04-04 08:12
by Roee Gavirel


3

In this case, no extra calculations are done.

However, there are some cases where a cast is technically a conversion, mostly with numeric input. For example the following could introduce runtime code (provided it is not optimised out, which in a small example like this you'd expect it to be):

int x = 42;
double d = (double)x;

Here the internal representation of an int and a double means you cannot just change how the compiler sees the variable, you have to change the data as well.

2012-04-04 08:16
by Matt


4

Here, it's purely a compile-time cast.

In the general case, a C-style cast could cause an instruction or two to be added, e.g. if needed to narrow/widen variables, but it's kind of rare and doesn't exactly affect performance.

The only run-time cast I know of is dynamic_cast.

2012-04-04 08:12
by Mehrdad
What about cast operators - Luchian Grigore 2012-04-04 08:25
@LuchianGrigore: The OP didn't ask about them... even the middle paragraph was extra info. (I don't think he was thinking about user-defined casts when he wrote his question either. - Mehrdad 2012-04-04 08:28


2

For your specific example, it's just to bypass the compiler. You're basically saying "I know this is not a char*, but I know what I'm doing, trust me".

Hoewver, if you have a user-defined type, you can overload the cast operator and it will perform the operations you tell it to:

struct A
{
   char* x;
   A() : x("abc") {}
   operator char() { return x[0]; }
   operator char*() { return x; }
};

int main()
{
   A a;
   char x = (char)a;   // x == 'a'
   char* y = (char*)a; // y == "abc"
   return 0;
}
2012-04-04 08:14
by Luchian Grigore


1

It depends on the cast, which I find slightly unsatisfying about C. I would rather there were separate mechanisms for converting one type to another and treating a block of memory as if it were a specific type.

For pointers, however, it's always just a compile-time thing. A char* has exactly the same representation as a void* (they're just a memory address), so there's nothing to do to convert them.

2012-04-04 08:15
by Ben
Well, that's fixed in C++ with reinterpret_cast and so on - Oliver Charlesworth 2012-04-04 08:18
Ads