J
Jef Driesen
Hi,
Suppose I have two distinct data structures:
typedef struct foo_t {
...
} foo_t;
typedef struct bar_t {
...
} bar_t;
and a function that receives a pointer to such a structure, together with a type
to indicate which structure is being passed:
typedef enum data_type_t {
DATA_TYPE_FOO,
DATA_TYPE_BAR
} data_type_t;
void myfunction (data_type_t type, void *data)
{
foo_t *foo = data;
foo_t *bar = data;
switch (type) {
case DATA_TYPE_FOO:
/* Use foo here */
break:
case DATA_TYPE_BAR:
/* Use bar here */
break:
default:
return;
}
}
A typical usage would be like this:
int main(void)
{
foo_t foo;
bar_t bar;
myfunction (DATA_TYPE_FOO, &foo);
myfunction (DATA_TYPE_BAR, &bar);
return 0;
}
Is it portable to replace the separate variables and explicit casts with a union?
typedef union foobar_t {
bar_t bar;
foo_t foo;
} foobar_t;
void myfunction (data_type_t type, void *data)
{
foobar_t *foobar = data;
switch (type) {
case DATA_TYPE_FOO:
/* Use foobar->foo here */
break:
case DATA_TYPE_BAR:
/* Use foobar->bar here */
break:
default:
return;
}
}
I think this is a portable construct, but I'm not 100% sure. Note that it's not
my intent to try to interpret a foo_t as a bar_t. The main purpose of the union
is to improve the readability of the code (my real code has many more foo and
bar structs).
Jef
Suppose I have two distinct data structures:
typedef struct foo_t {
...
} foo_t;
typedef struct bar_t {
...
} bar_t;
and a function that receives a pointer to such a structure, together with a type
to indicate which structure is being passed:
typedef enum data_type_t {
DATA_TYPE_FOO,
DATA_TYPE_BAR
} data_type_t;
void myfunction (data_type_t type, void *data)
{
foo_t *foo = data;
foo_t *bar = data;
switch (type) {
case DATA_TYPE_FOO:
/* Use foo here */
break:
case DATA_TYPE_BAR:
/* Use bar here */
break:
default:
return;
}
}
A typical usage would be like this:
int main(void)
{
foo_t foo;
bar_t bar;
myfunction (DATA_TYPE_FOO, &foo);
myfunction (DATA_TYPE_BAR, &bar);
return 0;
}
Is it portable to replace the separate variables and explicit casts with a union?
typedef union foobar_t {
bar_t bar;
foo_t foo;
} foobar_t;
void myfunction (data_type_t type, void *data)
{
foobar_t *foobar = data;
switch (type) {
case DATA_TYPE_FOO:
/* Use foobar->foo here */
break:
case DATA_TYPE_BAR:
/* Use foobar->bar here */
break:
default:
return;
}
}
I think this is a portable construct, but I'm not 100% sure. Note that it's not
my intent to try to interpret a foo_t as a bar_t. The main purpose of the union
is to improve the readability of the code (my real code has many more foo and
bar structs).
Jef