C++ Casting – Which to Use: static_cast or reinterpret_cast?

c++casting

int i = 1000;
void *p = &i;

int *x = static_cast<int*>(p);
int *y = reinterpret_cast<int*>(p);

which cast should be used to convert from void* to int* and why?

Best Answer

static_cast provided that you know (by design of your program) that the thing pointed to really is an int.

static_cast is designed to reverse any implicit conversion. You converted to void* implicitly, therefore you can (and should) convert back with static_cast if you know that you really are just reversing an earlier conversion.

With that assumption, nothing is being reinterpreted - void is an incomplete type, meaning that it has no values, so at no point are you interpreting either a stored int value "as void" or a stored "void value" as int. void* is just an ugly way of saying, "I don't know the type, but I'm going to pass the pointer on to someone else who does".

reinterpret_cast if you've omitted details that mean you might actually be reading memory using a type other than the type is was written with, and be aware that your code will have limited portability.

By the way, there are not very many good reasons for using a void* pointer in this way in C++. C-style callback interfaces can often be replaced with either a template function (for anything that resembles the standard function qsort) or a virtual interface (for anything that resembles a registered listener). If your C++ code is using some C API then of course you don't have much choice.