Let's say we have this structure with 4 float
values and a float
array with 4 elements.
Is it then undefined behavior or not to access the array as a Foo
instance and change the array elements through that instance?
struct Foo
{
float a;
float b;
float c;
float d;
};
float values[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
int main()
{
auto& floats = *reinterpret_cast<Foo*>(values);
floats.a = 0.0f;
floats.b = 0.0f;
floats.c = 0.0f;
floats.d = 0.0f;
}
Compile and run online: http://cpp.sh/6y7m
Yes, it is an undefined behavior indeed. It violates so-called strict aliasing rule - which prohibits access to the object through unrelated pointer (I won't dwell into details of what is unrelated here, unless specifically asked).
However, an array of floats to a struct is unrelated.
Here is an extract from Standard (3.10 / 10):
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
— the dynamic type of the object,
— a cv-qualified version of the dynamic type of the object,
— a type similar (as defined in 4.4) to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
— an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
— a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
— a char or unsigned char type.