Does static casting really gve any overhead, when no real "conversion" is performed?
Consider the following:
I could have used c++ style casts but i don't think it matters. The point is, does this kind of casting really take any time; or is it solely to ensure type safety?
int i1 = 1;
char *pc = (char*)&i1;
int i2 = *(int*)pc;
These are not static_casts, but reinterpret_casts. I would guess that it won't take any time, and it does the opposite of type safety.
Casting can cause overhead, yes. Consider when you have a 32-bit integer variable and suddenly want to convert it to a 64-bit variable. Unless you're on a 64-bit system, it will generate a move overhead for transferring the data over to a temporary.
This example has overhead, yes.
Originally Posted by tra86
As soon as you take the address of a variable it must be stored in memory. So if i1 was in a register, it's not anymore.
Then the final line must reload from the address of pc. This is because the contents of that memory address could have changed by another process/thead since we wrote to it.
You're also declaring new pointer variables which need to be stored somewhere, and that'll have register usage or stack cost.
I think for this example it is possible for the compiler to optimise and assign the constant 2 to both variables.
int i = 1;
char c = 2;
i = (int)c; // overhead -- value of c must be sign extended
c = (char)i; // overhead -- value of i must have top bits masked