Keloo
Keloo

Reputation: 1408

C++ anonymous union redeclaration error

I want to create a struct that can be used to store 3D coordinates or a linear equation. Here is the code:

struct myStruct {
    union {
        // coordinates (3d)
        struct {
            int x,y,z;
        };
        // linear equation (ax+b)
        struct {
            int a,b,x;
        };
    };
};

And I get the following error:

error: redeclaration of ‘int myStruct::<anonymous union>::<anonymous struct>::x’

I'm on linux mint 18.04, g++ (5.4.0), compile with --std=c++11.

I understand the problem. But have few questions.

  1. I saw something related working on windows, why?
  2. What is the best way to implement it so it works well on both (linux/win)?

Upvotes: 3

Views: 464

Answers (2)

Jonas
Jonas

Reputation: 7017

Just to complement the answer by user463035818. You can simplify your union a bit, by declaring the members directly, e.g.:

struct myStruct {
    union {
        // coordinates (3d)
        struct {
            int x,y,z;
        } coord;
        // linear equation (ax+b)
        struct {
            int a,b,x;
        } lin_eq;
    };
};

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123069

Just give them names. This should be fine:

struct myStruct {
    union {
        struct coordinates { int x,y,z; };
        struct linear_equation { int a,b,x; };
        coordinates coord;
        linear_equation lin_eq;
    };
};

I also allowed myself to add some members to the union. However, the two structs have members of same types and quantity, so imho entering the trouble of using a union is questionable.

Upvotes: 1

Related Questions