Click here to Skip to main content
15,888,242 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi Eveybody.

i searched around, googled and did not find definite answer to this.

some one said that C++ static_cast does not cost anything for pointers, is this true ?
and how does static_cast differ from C style casts ?

also

is C style casting / C++ static cast expensive, in terms of CPU cycles ( not compile time, runtime )

its for casting of
C++
LPVOID


i guess this is premature optomization.

Sorry if this is a repost :)

Thanks in Advance.
Posted

I'm a little too lazy to research before I answer, though I think you'll find that any pointer casting is essentially going to be for free. Though this would not be the case for casting say, a double to an int, for instance.

A pointer is always a pointer.The only thing that changes is the type of data it points to. The same can't be said for a number. Numbers come in all sorts of different types - bytes, words, ints, shorts, longs, doubles, floats etc, etc. So, to cast from one to another does necessarily involve a conversion of some type. While it is true that the performance hit will vary depending on the conversion happening, there will always be a conversion.

If on the other hand we look at pointers, we can see that the same problem does not need to be traversed. On a 32 bit system, a pointer is 32bits long. As I mentioned, it doesn't matter what type of data it actually points to, the pointers are all still the same size and refer to the same thing - a memory location. In my understanding, performing a cast on a pointer simply alerts the compiler to the data type that this pointer will now be used to access. This is important when the compiler calculates offsets into arrays or you (the programmer) does manual pointer arithmetic.


If I could respectfully add, there are other (far)more important things to look at when optimizing. If you've not already, I'd suggest running your code through a profiler and seeing where all of the execution time is being spent.
Cheers,
S
 
Share this answer
 
A more detailed answer about static_cast is here[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Aug-11 22:41pm    
Referenced article does provide pretty good explanation of things, my 5. Zero-cost case is reinterpret_cast.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900