I recently came across the strict aliasing rule, but I'm having trouble understanding how to use void * to perform type punning without breaking the rule.
I know this breaks the rule:
int x = 0xDEADBEEF;
short *y = (short *)&x;
*y = 42;
int z = x;
And I know that I can safely use a union in C99 for type-punning:
union{
int x;
short y;
} data;
data.x = 0xDEADBEEF;
data.y = 42;
int z = data.x;
But how do I use void * to safely perform type-punning in C99? Is the following correct:
int x = 0xDEADBEEF;
void * helper = (void *)&x;
short *y = (short *)helper;
*y = 42;
int z = x;
I suspect that code will still break the strict aliasing rule since the memory at variable x's address can be modified by both x and a dereferenced y.
If type-punning is undefined via void *, what is the purpose of the void * in C99?