C++ – static_cast wchar_t* to int* or short* – why is it illegal

ccastingwchar-t

In both Microsoft VC2005 and g++ compilers, the following results in an error:

On win32 VC2005: sizeof(wchar_t) is 2

wchar_t *foo = 0;
static_cast<unsigned short *>(foo);

Results in

error C2440: 'static_cast' : cannot convert from 'wchar_t *' to 'unsigned short *' ...

On Mac OS X or Linux g++: sizeof(wchar_t) is 4

wchar_t *foo = 0;
static_cast<unsigned int *>(foo);

Results in

error: invalid static_cast from type 'wchar_t*' to type 'unsigned int*'

Of course, I can always use reinterpret_cast. However, I would like to understand why it is deemed illegal by the compiler to static_cast to the appropriate integer type. I'm sure there is a good reason…

Best Answer

You cannot cast between unrelated pointer types. The size of the type pointed to is irrelevant. Consider the case where the types have different alignment requirements, allowing a cast like this could generate illegal code on some processesors. It is also possible for pointers to different types to have differrent sizes. This could result in the pointer you obtain being invalid and or pointing at an entirely different location. Reinterpret_cast is one of the escape hatches you hacve if you know for your program compiler arch and os you can get away with it.