Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Union Polymorphism within Arrays

Given the following:

typedef struct{
...
...
} A;

typedef struct{
...
... 
} B;

typedef union __attribute__((transparent_union)) {
    A a;
    B b;
} C;

If I declare a function

myMethod(C){
...
}

The following is legal without explicit casting:

A myA;
B myB;

meMethod(myA);
myMethod(myB);

(from: "c unions and polymorphism")

However, why is the following not allowed:

C cArray[2];
c[0]=myA;
c[1]=myB;

This gives an incompatible type error without explicit casting. Is there any way to avoid explicit casting?

like image 585
AFS Avatar asked May 23 '12 15:05

AFS


1 Answers

The GCC documentation states:

This attribute, attached to a union type definition, indicates that any function parameter having that union type causes calls to that function to be treated in a special way.

In other words, the transparency only applies to function parameters.

like image 177
David Heffernan Avatar answered Sep 26 '22 13:09

David Heffernan