Search code examples
cunions

Seeking C Union clarity


typedef union {
    float flts[4];
    struct {
        GLfloat r;
        GLfloat theta;
        GLfloat phi;
        GLfloat w;
    };
    struct {
        GLfloat x;
        GLfloat y;
        GLfloat z;
        GLfloat w;
    };
} FltVector;

Ok, so i think i get how to use this, (or, this is how i have seen it used) ie.

FltVector fltVec1 = {{1.0f, 1.0f, 1.0f, 1.0f}};
float aaa = fltVec1.x;
etc.

But i'm not really groking how much storage has been declared by the union (4 floats? 8 floats? 12 floats?), how? and why? Also why two sets of curly braces when using FltVector {{}}?

Why use a union at all? Why not do..

   struct FltVector {
        GLfloat x;
        GLfloat y;
        GLfloat z;
        GLfloat w;
   }

?

Any pointers much appreciated (sorry for the pun)


Solution

  • if sizeof(GLfloat) == sizeof(float) then, 4 floats have been allocated.

    flts[0], r and x will all refer to the same piece of memory here.

    In a union, every different variable declared in the union refers to the same piece of memory.

    Here we have 3 variables, 2 structs and an array, and each of them start at the same point in memory.