heavyz said:
In C, if i want to declare a struct, there are 3 methods to do so:
1: struct dummy { ... };
2: typedef struct { ... } dummy;
3: typedef struct _dummy { ... } dummy;
Usually i use the first method to declare my structs, but in many open
source projects (such as libxml2), the third method is used. I am just
curious about the difference.. Would somebody tell me which method is
recommended, and why? Thanks in advance.
#1 is a structure-type-definition. It is sufficient and rarely is more
needed. The
type thoughout the code is 'struct dummy' unless there is a later
typedef.
#2 and #3 are used to provide an alias for the struct.
In #2, there is no alias tag and so the type must be 'dummy' throughout.
This hides the fact that it is a struct and is probably a bad idea.
In #3, you create two names for the type, 'struct _dummy' and 'dummy'.
It is bad idea to use identifiers that begin with underscores unless you
are thoroughly familiar with the exact restrictions on such names. That
you are asking this question suggests that you are not. So #3 could be
done as either (note the absence of the underscore)
3a. typedef struct dummy { /* ... */ } dummy;
or in two parts;
3b. struct dummy { /* ... */ }; /* structure-type-definition */
typedef struct dummy dummy; /* typedef creating alias */
I prefer #1 in almost all situations.
#2 is probably better than your #3 or my #3a or #3b, since there is a
point to not having two ways of identifying the type. Of #3, #3a, and
#3b, #3 is the worst. #3b has real uses: namely to provide a
structure-type-definition in implementation files and providing a
typedef in a header where you want to make the type opaque to the user,
and he will refer to objects only through pointers to them.
Decide how you want the programmer to refer to a struct. If you want
him to use 'struct dummy', use #1. If you want him to use 'dummy', use
#2. If you want opaque datatypes referred to though pointers of the
type 'dummy *', use #3b.