Sense of Unions?

ok, to my understanding a Union is identical to a structure but all union variables occupy the same memory location? Please correct me if I am wrong. So would the sense of using a Union rather than a struct be simply for memory advantages? Would it just be better practice to use a Union instead if there are multiple variables of different data types? Thanks for the claification in advance.
closed account (zb0S216C)
gmenfan83 wrote:
ok, to my understanding a Union is identical to a structure but all union variables occupy the same memory location?

Correct. If you didn't know already, the size of a union is equivalent to the size of the biggest member.

gmenfan83 wrote:
So would the sense of using a Union rather than a struct be simply for memory advantages?

Yes, they save memory, but at the cost of maintaining only 1 possible value.

gmenfan83 wrote:
Would it just be better practice to use a Union instead if there are multiple variables of different data types?

Yes, it would, I guess. What you're referring to is called a variant. A variant is a structure that is capable of storing multiple types, but can only store 1 type of value at a time. Variants are normally implemented with unions.

There are other uses for unions, however, such as quick-and-dirty type-casting. For instance:

1
2
3
4
5
6
template <typename Type_A, typename Type_B>
union Dirty_Cast
{
    Type_A *A;
    Type_B *B;
};

The problem with the above is that is doesn't prevent clumsy casts.

Wazzak
Last edited on
Thanks for the explanation Framework.
Topic archived. No new replies allowed.