P
pozz
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.
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.