title: Exception to strict aliasing rule in C from 6.5.2.3 Structure and union members
body: <p>Quote from C99 standard:</p>
  <blockquote>
  <p>6.5.2.3</p>
  <p>5 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, <strong>it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible.</strong> Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.</p>
  </blockquote>
  <p>There is example for this case:</p>
  <pre><code>// The following code is not a valid fragment because
  // the union type is not visible within the function f.
  
  struct t1 { int m; };
  struct t2 { int m; };
  
  int f(struct t1 *p1, struct t2 *p2)
  {
      if (p1-&gt;m &lt; 0)
          p2-&gt;m = -p2-&gt;m;
      return p1-&gt;m;
  }
  
  int g()
  {
      union
      {
          struct t1 s1;
          struct t2 s2;
      } u;
  
      /* ... */
      return f(&amp;u.s1, &amp;u.s2);
  }
  </code></pre>
  <p>I have added few changes:</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  struct t1 { int m; };
  struct t2 { int m; };
  
  union u
  {
      struct t1 s1;
      struct t2 s2;
  };
  
  int foo(struct t1 *p1, struct t2 *p2)
  {
      if (p1-&gt;m)
          p2-&gt;m = 2;
      return p1-&gt;m;
  }
  
  int main(void)
  {
      union u u;
      u.s1.m = 1;
      printf(&quot;%d\n&quot;, foo(&amp;u.s1, &amp;u.s2));
  }
  </code></pre>
  <p>As you can see I have moved union declaration outside so it would be visible in foo(). According to the comment from standard, this should have made my code correct but it looks like strict aliasing still breaks this code for clang 3.4 and gcc 4.8.2.</p>
  <p>Output with -O0:</p>
  <blockquote>
  <p>2</p>
  </blockquote>
  <p>Output with -O2:</p>
  <blockquote>
  <p>1</p>
  </blockquote>
  <p>for both compilers.</p>
  <p>So my question is:</p>
  <p>is C really relies on union declaration to decide if some structures are exception to strict aliasing rule? Or both gcc/clang have a bug?</p>
  <p>It seems really broken to me, because even if function and union are both declared in the same header, this does not guarantee that the union is visible in translation unit with body of the function.</p>