Reputation: 19463
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.
Upvotes: 3
Views: 3437
Reputation: 7160
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.
Upvotes: 5
Reputation: 71545
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.
Upvotes: 1
Reputation: 258638
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;
}
Upvotes: 2
Reputation: 210755
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
.
Upvotes: 5