26 ms·
You basically split it up in a similar way that you'd use in an OO language, except you don't have inheritance and only have composition. Specifically, you brea
by yoklov 13y ago
You basically split it up in a similar way that you'd use in an OO language, except you don't have inheritance and only have composition. Specifically, you break apart the logically distinct portions of your structs and you make them structs themselves. E.g. compare (trivial examples, but you get the idea).
/* okay */
struct monster {
unsigned id;
int x, y, hp;
/* etc. */
};
/* better */
struct point { int x, y; };
struct monster {
unsigned id;
struct point pos;
int hp;
};
This also allows a form of inheritance. For example if you have
struct bad_monster {
struct monster base;
int badness; /* your imagination is the limit. */
};
/* this is safe */
struct bad_monster bad;
struct monster *some_monster = (struct monster *)&bad; /* equivalently &bad.base */
some_function_expecting_a_monster(some_monster);
/* only safe if it was originally a struct bad_monster */
struct bad_monster *bad_ptr = (struct bad_monster *)some_monster;
Those are the ways I tend to break up structs when writing C code. Basically by using lots of composition.
- acqq 13y agoAnd the good aspect of C is the "flatness" of the structures: they are not "objects" with the hidden content and associated functions managing it. It's a way for the programmer to organize the data as efficiently as possible.