c.***@seznam.cz wrote, On 09/10/07 07:34:
Hi,
I have found a piece of code which declares union like this:
union vector_s {
struct {float x,y,z};
float m[3];
} v;
C does not have anonymous struct/union members so you actually need:
union vector_s {
struct {float x,y,z;} s;
float m[3];
} v;
there is unnamed structure m ( matrix 1x3 ) which has same offset as
x, so they are aligned properly. The problem I have is, whether I can
safely write data to, lets say, v.m[2] and read same data from v.z?
Like:
v.m[2] = 1.25f;
assert (v.z == 1.25f);
I tried to find answer myself, but i was not successfull.
Please, could you enlighten me?
You cannot do it safely since the compiler is allowed to insert padding
between structure members but not between array members. The standard
does not even require that it has a good reason to do it! So whilst
v.m[0] will be at the same address as v.s.x, there is no guarantee that
v.m[1] is at the same address as v.s.y
The correct thing to do is either use an array OR a struct. If you want
to use a struct but still have names you can do
enum {X, Y, Z, NO_ELEMENTS};
float v[NO_ELEMENTS];
Then use v[Z]
Finally, it is almost always better to use double. A lot of the time
floats get promoted to double and where they are different szes float is
often *slower* than double.
--
Flash Gordon