Is this fragment of code a violation of strict aliasing rule:
int main()
{
short tab[] = {1,2,3,4};
int* ps = (int*)(&tab[0]);
int i = *ps;
}
I do know that if this was in the opposite way it would be a violation
int main()
{
int tab[] = {1,2,3,4};
short* ps = (short*)(&tab[0]);
short s = *ps;
}
Of course that violates strict aliasing. The code is accessing values through a pointer of a different type, and it isn't
char*
.The code is allowed to return 1 there. Because a write to *ps is a write to an
int
and according to strict aliasing rules anint
pointer cannot possibly point to ashort
. Therefore the optimizer is allowed to see that thetab
array is not modified, optimize out theif
statement because it is always true, and rewrite the entire function to simply return 1.