You should never cast pointers of different types. When the pointed-to types have different representations, such forced conversions simply don't make any sense. For example, double
and float
might not have the same size or representation, in which case pointer conversions between the two types are blatantly incorrect.
But even if you know that the different types have the same representation, the pointer conversion is still not safe! Because of the strict aliasing rule, such conversions might yield incorrectly generated code by the compiler, since the compiler is free to assume that you would never access the given data through a pointer of an incorrect type. So it might optimize away portions of your code.
It is only safe to cast any given pointer:
- To/from a pointer pointing at the same qualified type (*).
- To a pointer pointing at the same type, but with more qualifiers specified (*).
- To/from
void
pointer.
- To a null pointer.
- To a pointer to byte integer types, such as
char*
or uint8_t*
.
All other cases of pointer to pointer conversions are bugs and invoke undefined behavior as soon as you access the pointed-to data. Including casts from char*
to a pointer to a larger type.
(*) Qualified type means, a type with qualifiers such as const
or volatile
present. For example it is safe to convert from int*
to const int*
but never the other way around.