Union of same type in C++

Viewed 2484

Whenever I see examples of union, they are always different types. For example, from MSDN:

// declaring_a_union.cpp
union DATATYPE    // Declare union type
{
    char   ch;
    int    i;
    long   l;
    float  f;
    double d;
} var1;          // Optional declaration of union variable

int main()
{
}

What happens if I have a union (in this case anonymous, but that shouldn't matter) like this:

union
{
    float m_1stVar;
    float m_1stVarAlternateName;
};

Regardless of whether this is good practice or not, will this cause any issues?

3 Answers

This is legal and very useful in situations where you have different contexts, where different names would be more appropriate. Take a four member vector vec4 type for example (similar to what you'd find in GLSL):

vec4 v(1., 1., 1., 1.);

// 1. Access as spatial coordinates
v.x;
v.y;
v.z;
v.w;

// 2. Access as color coordinates (red, green, blue, alpha)
v.r;
v.g;
v.b; 
v.a;

// 3 Access as texture coordinates
v.s;
v.t;
v.p;
v.q;

A vec4 may only have four members of the same type, but you'd use different names to refer to the same objects, depending on the context.

An issue would arise only if you want to have unique values for the two variables. In your use-case, it should work fine.

Related