4

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;
timrau
  • 22,578
  • 4
  • 51
  • 64
HellGate
  • 708
  • 1
  • 5
  • 20

1 Answers1

7

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
};
Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • yep thats true. i conefused myself a bit by trying make both useable without the "size_" prefix and somehow forgott that this did not group x and y together. thanks for your quick response. – HellGate Jul 02 '14 at 15:33