I've got a question about strict-aliasing rules, unions and standard. Assume we have the following code:
#include <stdio.h>
union
{
int f1;
short f2;
} u = {0x1};
int * a = &u.f1;
short * b = &u.f2;
int main()
{
u.f1 = 1;
*a += 1;
u.f2 = 2;
*b *= 2;
printf( "%d %hd\n", *a, *b);
return 0;
}
Now let's look how it works:
$ gcc-5.1.0-x86_64 t.c -O3 -Wall && ./a.out
2 4
$ gcc-5.1.0-x86_64 t.c -O3 -Wall -fno-strict-aliasing && ./a.out
4 4
We can see that strict-aliasing breaks dependencies. Moreover it seems to be a correct code without breaking strict-aliasing rule.
- Does it turn out than in case of union fields an object laying at the address is compatible with all types of union members?
- If 1 is true what should compiler do with pointers to union members? Is it a problem in the standard, that allows such compiler behavior? If not - why?
- Generally speaking different behavior of the compiler with the correct code is inadmissible in any case. So it seems to be a compiler bug too (especially if taking address to union field will be inside functions, the SA does not breaks dependence).
-fno-strict-aliasing
or-O0
. – Bryophyte