structure typedefs

Bob Goudreau goudreau at larrybud.rtp.dg.com
Fri Mar 30 09:52:37 AEST 1990


In article <1990Mar28.150755.6803 at uunet!unhd>, rg at uunet!unhd (Roger
Gonzalez ) writes:
> 
> I seem to recall even seeing this:
> 
> typedef struct  foo {
>     ..
>     struct foo *next;
> } foo;
> 
> foo bar;
> 
> Which looks to me like it should cause an error.  Please enlighten me as to
> the subtleties of this.  I'm not a novice C programmer, and I've been using
> structures for years, and I know how to make them work, but I've never really
> understood exactly what was going on internally.  Email if possible; I don't
> read this group often.

There's nothing wrong with it; it's perfectly legal C.  The thing to
remember is that typedef names and structure names basically live in
two different namespaces.  There is no potential for ambiguity because
structure names must always be preceeded by the word "struct" and
typedef names can *never* be preceded by "struct".  So, to continue
your example, the following two variables have the same underlying
type:

	foo bar;
	struct foo bletch;

Of course, whether naming structs and types in this manner is good
programming practice is another question entirely.  The coding
standards for the project that I work on require that we always
create a typedef for any structs we invent.  Whenever possible (which
is most of the time), the struct itself has no self-references and
can thus be unnamed:

	typedef struct

	{
	a_type	a;
	b_type	b;

	}	foo_bar_type;


Only when there is need for self-reference does the structure get a
name, and to avoid confusion that name is produced by replacing the
"_type" in the typedef name with "_tag":

	typedef struct foo_whiz_tag

	{
	a_type			a;
	b_type			b;
	struct foo_whiz_tag *	next;

	}	foo_whiz_type;

------------------------------------------------------------------------
Bob Goudreau				+1 919 248 6231
Data General Corporation
62 Alexander Drive			goudreau at dg-rtp.dg.com
Research Triangle Park, NC  27709	...!mcnc!rti!xyzzy!goudreau
USA



More information about the Comp.lang.c mailing list