简体   繁体   中英

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

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.

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.

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, eg 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 .

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM