News for hackers. Stuff that matters.
Re:Memcpy vs. memmove by stephencanon on Tuesday December 02, 2014 @06:40AM (#8686639)
C11 explicitly blessed unions for type-punning as well as memcpy (actually, C99 TC2 did). That said, people should just use memcpy.
Re:Memcpy vs. memmove by nkurz on Tuesday December 02, 2014 @05:17PM (#8690363)
Yes, it's now in the standard (someone in the thread I linked pointed to TC3 draft, §6.5.2.3, footnote 82) but apparently there are issues with the way GCC implements in its default dialect that make it unsafe. More Mike Stump:

  >>> So what about using a union?
  >>
  >> Most people screw it up, the rules for it working are slightly odd.
  >> Those rules are not standard[1], rather they are gcc specific, so in very
  >
  >Ouch, so what you are saying is that this is one of those (according to 
  >Nick M) barely defined areas of the language?

  What I am saying is that it is defined to not work in the language
  standard gcc implements by default.  There is no barely, there is no
  defined.  As an extension to the language standard, gcc implements
  (defines) a few things so that users can make some non-standard things
  always work.  I say slightly odd, as the rules are just a tad harder
  than trivial.
I prefer the union approach to memcpy() because I can more easily reason about its behaviour, but veiled warnings from GCC maintainers scare me away from it. But perhaps I misunderstand the warning.

For that matter, I prefer simple casts to unions, and while I agree the spec makes it undefined, I don't yet see why all common implementations couldn't simply make it work in all reasonable cases. I'm currently trying to get used to using memcpy() for type annotation, but it still feels unnatural to write a function I don't want executed (yes, I have trouble with setters/getters too).

What I'd like is to have a way to specify to the compiler that I want it to compile the code I give it as written as best as it can, rather than optimizing it out as undefined. As it is, I often resort to inline assembly if I actually want an operation to happen. It seems like there should be an intermediate approach, a hypothetical '#pragma "dwim"' that could avoid this.