TheGreatB3
TheGreatB3

Reputation: 75

Can I use a union to express a struct and multiple packed members?

Say I have a struct, ivec2:

typedef struct ivec2 {
    int x, y;
} ivec2;

I'd like to know if I can make a union similar to the following:

union rectangle {
    ivec2 size; // 8 bytes; members: int x, y;
    int width, height; // 4 + 4 bytes
};

where width corresponds to size.x, and height corresponds to size.y.

I've seen that it's possible to do this:

union rectangle {
    ivec2 size; // 8 bytes
    int arr[2]; // 4 + 4 bytes
};

but can I do it with separate members?

This image shows what I'm getting at:

Diagram of union

Upvotes: 0

Views: 86

Answers (1)

Thomas Jager
Thomas Jager

Reputation: 5265

What you want to do is nest an anonymous struct within the union.

Instead of:

union rectangle {
    ivec2 size;
    int width, height;
};

do:

union rectangle {
    ivec2 size;
    struct {
        int width;
        int height;
    };
};

Upvotes: 1

Related Questions