Fred
4/14/2011 3:12:00 PM
On Apr 14, 5:23 am, pozz <pozzu...@gmail.com> wrote:
> As someone probably rememeber, I use a quite old C compiler for an
> embedded 16-bit processor with some limitations.
> One of these regards the initialization of arbitrary members of union
> or struct. For example, I can't do the following:
>
> const struct {
> int type;
> union {
> int x;
> double y;
> } u;
> } mystruct = { TYPE_Y, {.y = 3} };
>
> I was thinking to split a struct like the above in two different
> struct and a "parent" struct:
>
> typedef struct {
> int type;
> int x;
> } mystruct_x;
> typedef struct {
> int type;
> double y;
> } mystruct_y;
> typedef struct {
> int type;
> } mystruct;
>
> The parent struct contains only the common members (in this case, only
> the member type).
> With the above definitions, I'd like to write something like:
>
> const mystruct_x sx = { TYPE_X, 10 };
> const mystruct_y sy = { TYPE_Y, 5.3 };
> const mystruct *s;
> ...
> s = (const mystruct *)&sx;
> ...
> if (s->type == TYPE_X) {
> const mystruct_x *sx = (const mystruct_x *)s;
> printf("x=%d\n", sx->x);
> } else if (s->type == TYPE_Y) {
> const mystruct_y *sy = (const mystruct_y *)s;
> printf("y=%3.1f\n", sy->y);
> }
>
> I'm asking if the cast from (mystruct_x *) to (mystruct *) and the
> contrary is correctly interpreted.
Copy how the Unix XEvent structures do it:
typedef struct {
int type;
} MyStructAny;
typedef struct {
int type;
int x;
} MyStructInt;
typedef struct {
int type;
double y;
} MyStructDouble;
typedef union myStruct {
int type;
MyStructAny my_any;
MyStructInt my_a;
MyStructDouble my_b;
} MyStruct;
const MyStructInt sx = { TYPE_X, 10 };
const MyStructDouble sy = { TYPE_Y, 5.3 };
const MyStruct *s;
...
s = (const MyStruct *)&sx;
...
if (s->type == TYPE_X) {
const MyStructInt *sx = (const MyStructInt *)s;
printf("x=%d\n", sx->x);
} else if (s->type == TYPE_Y) {
const MyStructDouble *sy = (const MyStructDouble *)s;
printf("y=%3.1f\n", sy->y);
}
--
Fred K