[OCLUG-devel] Single Element Structures

Christopher Smith x at xman.org
Fri Sep 2 15:05:32 PDT 2005


Doug Jolley wrote:
> Hi --
> 
> I am a real newbie to C and in way over my head on a project that I'd
> really like to get to work.  I'm thinking that the thing to do may be to
> try to get some help at the next OCLUG meeting; but, in the meantime I'm
> going to try to muddle along as best I can.
> 
> To continue my muddling, I have encountered the following type definition:
> 
> typedef struct {
>     node* head;
> } llist;
> 
> My question is:  Why would anyone go to the trouble of defining a
> structure with only one element in it?  I thought the essence of
> structures was that they contained a collection of dissimilar data
> elements.  I'm sure the guy that did this had a very good reason and I
> realize that I'm asking a question without giving a lot of context; so,
> from what I've given there may be no answer.  Anyway, if an answer may
> be deduced from what I've given, I'd love to hear it.  Thanks for any input.

So, basically I can think of two good reasons why one might want to do this:

1) By defining it as a struct you leave open the option of adding more
fields later without majorly impacting code that uses the llist type.

2) It prevents random pointers from being coerced into to llist's. So,
if you have a function defined like this:

void safe_traverse_list(llist alist);

instead of this:

void traverse_list(node* alist);

The compiler catches things it otherwise would miss:

void* random_pointer;
traverse_list(random_pointer); /* compiler is happy with it */
safe_traverse_list(random_pointer); /* compiler complains */

--Chris


More information about the OCLUG-devel mailing list