Search code examples
c++strict-aliasing

Strict aliasing rule in array


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;
}

Solution

  • Of course that violates strict aliasing. The code is accessing values through a pointer of a different type, and it isn't char*.

    int main()
    {
        short tab[] = {1,2,3,4};
        int* ps = (int*)(&tab[0]);
        *ps = 3;
        if(tab[0] == 1) return 1;
        return 0;
    }
    

    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 an int pointer cannot possibly point to a short. Therefore the optimizer is allowed to see that the tab array is not modified, optimize out the if statement because it is always true, and rewrite the entire function to simply return 1.