[OCLUG-devel] Single Element Structures

Dan Stromberg strombrg at dcs.nac.uci.edu
Fri Sep 2 18:18:09 PDT 2005


On Fri, 2005-09-02 at 15:44 -0700, Christopher Smith wrote:
> Dan Stromberg wrote:
> > C can do ADT's pretty well really, except for the information hiding part.
> 
> How so? I mean:
> 
> struct foo {
>     int (*method1)();
>     void (*method2)(int);
>     void* data;
> };
> 
> may not be the prettiest thing, but it works quite well to hide the
> underlying data structures.

Yeah, it hides it all right.  It's of course -possible- to do this sort
of thing, even in assembly language, even in machine language, even on a
Turing Machine.  Most to all efforts in this direction end up
reinventing OO/OB languages' object models in a somewhat less convenient
way, but it's very possible - as a large example, consider GTK+, which
has a pretty OO/OB model, but is implemented in C, and then mapped to a
bunch of OO/OB languages from there...  Other than the poor type
checking, it's really not too gruesome.

> > Two common data representations that might be used internally by a stack
> > ADT (abstract data type) would be an array, or a linked list.
> 
> Yeah, but then you'd want to define it slightly differently from the
> example described:
> 
> struct ll_stack;
> struct array_stack;
> #ifdef USE_LINKED_LIST
> typedef ll_stack stack;
> #else
> typedef array_stack stack;
> #endif

Um, yeah.  typedef, #define, a magic #include, linking a different .o,
-Dfoo=bar, whatever.

> That way you can have both the array and linked list functions compiling
> successfully simultaneously (because they will use array_stack or
> ll_stack as their parameter types, not stack), and the stack-using code
> will just automagically link to the right one.

Nod.  Been there, done that, worth discussing anyway.

> > That way, any time I want to use a global variable
> > named "foo", I instead refer to "global.foo", making it a hair less
> > confusing when another programmer works on my code, or I revisit my own
> > code years later.  :)
> 
> Wouldn't it be simpler and just as good a hint to name the variable
> "global_foo"?

You know, I started out doing it with a global_ prefix... I just
migrated to the struct later.  Seems a little more aesthetic to me, but
C is very much a language that allows many styles.




More information about the OCLUG-devel mailing list