Search code examples
c++castingtype-safetyreinterpret-cast

C++ - Safety of reinterpret_cast for pointer-to-primitives


I've come across a piece of code in a project I'm evaluating, and wanted to know if the following cast is safe:

void func(unsigned long* input);
...
int data = 42;
func(reinterpret_cast<unsigned long*>(&data));  
// Casting to remove compiler warnings about data type not matching type expected

I know that with just simple C-style casting (ie: (unsigned long*)&data) that this is asking for trouble. Does reinterpret_cast automagically make this type of casting operating safe?

Thank you.


Solution

  • No it is not safe: the program behaviour is undefined.

    This is because the pointer types are unrelated.