The following code compiles and runs fine with gcc. But i wondered if such an union is define by the standard and if it works on all c compilers the same way. I know it will not work if, parameters of that functions are not pointers and not compatible with each other, but as long as all paramters are pointers and the number of parameters are the same there shouldn’t be a problem, or?
typedef struct node {
unsigned long int key;
} node_t;
typedef struct node1 {
unsigned long int key;
char *str;
} node1_t;
typedef struct node2 {
unsigned long int key;
void *data;
} node2_t;
typedef struct node3 {
unsigned long int key;
int numbers[256];
} node3_t;
int compare(node_t *a, node_t *b) {
printf("%ld ? %ld\n", c->key, d->key);
return c->key == d->key;
}
struct comp {
union {
int (*c0) (node_t *a, node_t *b);
int (*c1) (node1_t *a, node1_t *b);
int (*c2) (node1_t *a, node2_t *b);
int (*c3) (node1_t *a, node3_t *b);
int (*c4) (node2_t *a, node1_t *b);
int (*c5) (node2_t *a, node2_t *b);
int (*c6) (node2_t *a, node3_t *b);
int (*c7) (node3_t *a, node1_t *b);
int (*c8) (node3_t *a, node2_t *b);
int (*c9) (node3_t *a, node3_t *b);
} are;
};
int main(int argc, char *argv[])
{
node1_t a[] = {
{ 23477843258923UL, "Hello World" },
{ 10254892378892UL, "Hello Back" }
};
node2_t b[] = {
{ 83296783479803UL, NULL },
{ 52348237489832UL, (void *) &a[1] }
};
node3_t c[] = {
{ 91308823949203UL, { 3, 4, 5 } },
{ 17587832478823UL, {43, 43, 43, 86 } }
};
struct comp comp;
comp.are.c0 = compare;
comp.are.c1(&a[0], &a[1]);
comp.are.c2(&a[1], &b[0]);
comp.are.c3(&a[0], &c[1]);
comp.are.c8(&c[1], &b[1]);
}
The
unionis valid, but what you are doing with it is not. You cannot put something into theunionwith one type and then use it with another like the end ofmainis doing unless those types are convertible (thanks to @Christoph for that comment).