C Union Polymorphism in 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 legal without explicit casting:

 A myA; B myB; meMethod(myA); myMethod(myB); 

(from: " c alliances and polymorphism ")

However, why is the following unacceptable:

 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?

+6
source share
1 answer

The GCC documentation states:

This attribute, attached to the definition of a union type, indicates that any function parameter that has this type of union calls the function that needs to be processed in a special way.

In other words, transparency applies only to function parameters.

+3
source

Source: https://habr.com/ru/post/916468/


All Articles