Question about type punning: why does this code break strict aliasing rules:
int main()
{
int a = 1;
short j;
printf("%i\n", j = *((short*)&a));
return 0;
}
and this is not:
int main()
{
int a = 1;
short j;
int *p;
p=&a;
printf("%i\n", j = *((short*)p));
return 0;
}
Build by gcc -fstrict-aliasing
.
Thank you!
They both violate the strict aliasing rule, I am going to quote my answer here which says (emphasis mine going forward):
gcc
is a little more detailed in the documetation of-Wstrict-aliasing=n
here which says:and describes each level as follows:
So it is not guaranteed to catch all instances and different levels have different degrees of accuracy.
Typically the effect you are looking for can be accomplished using type punning through a union, which I cover in my linked answer above and gcc explicitly supports.