When is casting between pointer types not undefined behavior in C?

Basically:

  • a T * may be freely converted to a void * and back again (where T * is not a function pointer), and you will get the original pointer.
  • a T * may be freely converted to a U * and back again (where T * and U * are not function pointers), and you will get the original pointer if the alignment requirements are the same. If not, the behaviour is undefined.
  • a function-pointer may be freely converted to any other function-pointer type and back again, and you will get the original pointer.

Note: T * (for non-function-pointers) always satisfies the alignment requirements for char *.

Important: None of these rules says anything about what happens if you convert, say, a T * to a U * and then try to dereference it. That’s a whole different area of the standard.

Leave a Comment