Question

I declared this structure in global scope,

struct a{
int a;
int x;
union b{
int a;
int b;
int y;
};
};

And then declared an union inside main,

union b a;

And this is not giving any errors. But if declare union 'a' in the definition of structure, like:

struct a{
int a;
int x;
union b{
int a;
int b;
int y;
}a;
};

It gives error "duplicate member a". (WE USED THE SAME NAME 'a' IN THE PREVIOUS CASE) Why does one work and another does not?

Secondly, how can we use the union declared inside struct, independently, but can't use any other integer variable, say 'x'? Like, i can perform the following successfully:

union b z;  //works in this case, BUT not if we declare 'z' with the definition.
z.y=6;      //works
x=6;        //gives error

(i understand we are declaring union inside main, but its definition in inside the struct. Like, struct.union.union_variable makes sense, but having union.union_variable directly make it kind of independent. Shouldn't it be treated like 'x'?)

Was it helpful?

Solution

It gives error "duplicate member a". (WE USED THE SAME NAME 'a' IN THE PREVIOUS CASE) Why does one work and another does not?

Because your struct has now two members named a: first one is an int and second one is of type b (your union). You wouldn't be surprised to see this doesn't compile:

struct a {
    int a;
    float a;
};

In your case you have exactly same situation, imaging you defined b outside struct and you try to use it like this:

struct a {
    int a;
    union b a;
};

Secondly, how can we use the union declared inside struct, independently, but can't use any other integer variable, say 'x'? Like, i can perform the following successfully:

Where is x declared? You don't have any local variable named x (what you may have is a struct member named x but then you need such structure). One of following (according to what you're trying to do):

int x = 6;
struct a w;
a.x = 6;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top