Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct variable alias

i'm trying to create an alias for a variable inside a struct like this:

typedef struct {
    union {
        Vector2 position;
        float x, y;
    };
    union {
        Vector2 size;
        float width, height;
    };
} RectangleF;

(note that i didn't name the unions so i dont have to write: 'variable.unionname.x' etc.)

however i get a "Initializer overrides prior initialization of this subobject" warning when i create some constants of this struct:

static const RectangleF RectangleFZero = {
    .x = 0.0f,
    .y = 0.0f, // warning
    .width = 0.0f,
    .height = 0.0f // warning
}

is there anything wrong doing this? and if not, how can i get rid of this warning?

Edit: Solution i use now:

typedef struct {
    union {
        Vector2 position;
        struct { float x, y; };
    };
    union {
        Vector2 size;
        struct { float width, height; };
    };
} RectangleF;
like image 398
HellGate Avatar asked Nov 16 '25 03:11

HellGate


1 Answers

The issue is that your union is actually this:

typedef struct {
    union {
        Vector2 position;
        float x;
        float y;
    };
    union {
        Vector2 size;
        float width;
        float height;
    };
} RectangleF;

You could fix it by doing:

typedef struct {
    union {
        Vector2 position;
        struct {
            float x;
            float y;
        } position_;
    };
    union {
        Vector2 size;
        struct {
            float width;
            float height;
        } size_;
    };
} RectangleF;

And then do:

static const RectangleF RectangleFZero = {
    .position_.x = 0.0f,
    .position_.y = 0.0f,
    .size_.width = 0.0f,
    .size_.height = 0.0f
};

Additionally...

If your compiler supports C 2011's anonymous inner structs, then you can also do this:

typedef struct {
    union {
        Vector2 position;
        struct {
            float x;
            float y;
        };
    };
    union {
        Vector2 size;
        struct {
            float width;
            float height;
        };
    };
} RectangleF;

static const RectangleF RectangleFZero = {
    .x = 0.0f,
    .y = 0.0f,
    .width = 0.0f,
    .height = 0.0f
};
like image 72
Bill Lynch Avatar answered Nov 17 '25 17:11

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!