Home > Blogs > 30 C++ Tips in 30 Days: Tip # 4 Using static_cast instead of reinterpret_cast

30 C++ Tips in 30 Days: Tip # 4 Using static_cast instead of reinterpret_cast

By  Nov 22, 2007

Topics: Programming, C/C++

I'm not a big fan of C++ cast operators, to say the least. But these operators are here to stay, and they're used quite frequently in production code. Operator reinterpret_cast is used for casting pointers of two unrelated types, say date* to int*. You can avoid reinterpret_cast in such cases by using a two-phased static_cast, which is purportedly safer.

static_cast will convert pointers only if the types are related, or if the cast is to and from void*. If you want to convert char* to long *, you can't use static_cast as these two pointers are not related.

Using a two-phases conversion, you can still use static_cast for that purpose:
 

char * s;
//equivalent to reinterpret_cast<long*> (s):
long * ptr= static_cast<long*> (static_cast<void*>(s));

Not sure why some folks find this version more attractive than good old C-style cast, or reinterpret_cast but you might come across this idiom, so at least you can tell right away what such code really does.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.