Does this pointer casting break strict aliasing rule?-Collection of common programming errors
Yes, it breaks aliasing rules.
The cleanest fix for things like i = * ( long * ) &y;
would be this:
memcpy(&i, &y, sizeof(i)); // assuming sizeof(i) == sizeof(y)
It avoids issues with alignment and aliasing. And with optimization enabled, the call to memcpy()
should normally be replaced with just a few instructions.
Just as any other method suggested, this approach does not fix any problems related to trap representations. On most platforms, however, there are no trap representations in integers and if you know your floating point format you can avoid floating point format trap representations, if there are any.
Originally posted 2013-11-10 00:15:30.