I'm trying to understand the implications of the following statement in the C99 standard (C99; ISO/IEC 9899:1999 6.5/7)
An object shall have its stored value accessed only by an lvalue expression that has one of the following types 73) or 88):
(other statements unrelated to question omitted)
an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union)
Consider the following:
typedef struct MyComplex {
float real;
float imag;
} MyComplex;
MyComplex *carray = malloc(sizeof(*carray) * 10);
float *as_floats = (float *)carray;
Is this legal since the MyComplex
structure contains a compatible float
type for the as_floats
pointer?
What about the other way around? i.e:
float *farray = malloc(sizeof(*farray) * 10);
MyComplex *as_complex = (MyComplex *)farray;
In both cases, ultimately, everything we're dealing with here is a float
, so maybe it's ok? I'm just not sure.
I ask, because I'm dealing with a legacy code base that does this kind of stuff all over the place and so far, everything seems fine. But I feel like we're playing with fire here. Trying to figure out if I need to disable strict aliasing on the compiler command line or not.