David Brown wrote: > On 04/07/2011 18:57, Georg-Johann Lay wrote: >> Hi, >> >> this it not a question on GCC, so I apologize for asking a question on >> C strict aliasing rules here. As I know that some people reading this >> list are much more familiar with C standard than I am, allow me to ask >> that question, anyway. >> >> Suppose the following C code that tries to implement the standard >> copysign function, i.e. copy the sign of y into x and return that >> value. double be 64 bits wide: >> >> >> #define MASK ((unsigned short) 0x8000) >> >> double copysign (double x, double y) >> { >> unsigned short * const px = (unsigned short*)(char*)&x + 3; >> unsigned short * const py = (unsigned short*)(char*)&y + 3; >> >> *px = *px& ~MASK | *py& MASK; >> return x; >> } >> >> >> While I say that this code is not correct because it breaks C's strict >> aliasing rules (e.g C89/90, Chapter 6.3; C98/99, Chapter 6.5, Clause >> 7), some other person very well familiar with the standard claims that >> is correct and no problem. >> >> So I want to reassure me if the code is ok or not. >> >> I am aware of gcc's -f[no]-strict-aliasing switch, but that's rather >> technical detail to cope with such presumably incorrect code. >> >> Thanks, >> >> Johann >> >> BTW, gcc does just what I would expect: it returns x unchanged and >> that is not an "optimizer bug". >> > > Does it get compiled to an empty function? > > Anyway, you are correct that strict aliasing means that this function is > buggy - the compiler can assume that a "double" such as x or y cannot > share the same address as a "short" (or "unsigned short"), thus the > pointer "px" cannot point to x, thus x is not changed by the function, > and can be returned unchanged. Yes, that's what the function does: it's for a 32-bit machine and compiles to copysign: mov %e2, %d5, %d4 ret because the return register differs from input register. > It would be /far/ better to stick to char pointers - It's not up to me to change these sources or to fix malicious code by changing build options. I'm just the guy left with evaluation of some software package. Johann