Does this code violate strict aliasing?
struct {int x;} a;
*(int*)&a = 3
More abstractly, is it legal to cast between different types as long as the primitive read/write operations are type correct?
Does this code violate strict aliasing?
struct {int x;} a;
*(int*)&a = 3
More abstractly, is it legal to cast between different types as long as the primitive read/write operations are type correct?
First, it is legal to cast in C. §6.7.2.1/13:
The aliasing rule reads as follows (§6.5/7):
Here you would be accessing it via pointers of a "type compatible with the effective type of the object" and "an aggregate or union type that includes one of the aforementioned types among its members", so no problem with aliasing either. So in C, it is indeed perfectly legal to access the first member of a structure by casting the pointer to the structure to the type of the member in question.
In C++, however, you'll often find vtables and other things at the start of a C++ object. In your specific case, however, your structure is of standard layout, and so this is explicitly allowed (§9.2/20 in n3290, thanks Luc Danton! - C++03 apparently has a similar rule, expressed in terms of POD objects).