Hacker News new | ask | show | jobs
by Kristine1975 3836 days ago
IIRC unions are a common example.

If you mean type punning: That is fine in C (chapter 6.5.2.3 of the C11 Standard even mentions "type punning" in footnote 95), but not in C++, where it's undefined behavior.

I would just use memcpy. It works even when C code is compiled as C++, and modern compilers know what memcpy does and can optimize its call to a move operation: http://blog.regehr.org/archives/959

1 comments

Type punning is not fine in C99 - you need to use a correctly typed pointer or a char pointer.
You're right. Type punning via pointer cast, e.g.

  int i = ...
  float f = *(float*) &i;
is not fine (violates strict aliasing). Type punning via union, e.g.

  union { int i; float f; } u;
  u.i = ...
  float f = u.f;
is, though (but only in C).

Just use memcpy :-)