Search code examples
c++language-lawyerstrict-aliasing

Does the strict-aliasing rules apply across function calls?


About the example below, in f1, no alias occurs because p(void*) isn't accessible and p1 is the only pointer accessing memory. However, there is a pointer aliasing between p1(float*) and p2(int*) which is outside f1.
My question is that, is this alias illegal or not, that is, does the strict-aliasing rules apply across function calls ?

If this example is valid, what if the f1 is inlined ?

void f1(void *p)
{
  auto* p1 = static_cast<float*>(p);
  *p1 = 1.f;
}

int f2()
{
  int x = 1;
  auto* p2 = &x;
  f1(&x);
  *p2 = 1;
  return *p2;
}

Solution

  • It doesn't matter how many times you copy a pointer or pass it to somewhere else or how many times you convert it, the determining factor is always what's actually stored at that location.

    In your case, the only thing that matters is whether static_cast's argument actually is the address of a float, and it isn't.