I think this is done mostly because of the very mistaken idea that a struct and a type cannot have the same name. In other words, that somehow
struct MyStruct;
typedef struct MyStruct MyStruct;
will collide in strange ways because the struct
and the typedef
have the same name. This is wrong in C. The name of a struct is considered a tag, whereas a typedef creates a type name. These live in two different namespaces and will not collide. In my opinion, it makes a lot more sense for the tag of the struct to be the same as the typedef, assuming you use a typedef at all. In C, you must always reference a struct with the struct keyword. For example, if you define
struct MyStruct;
but do not make a typedef, then the following is invalid:
void myfunction()
{
MyStruct var; /* compiler error: MyStruct is not defined. */
struct MyStruct var2; /* this is OK, MyStruct is a valid name for a struct. */
}
If you want to define variables (or arguments) of type MyStruct
in C, you must provide a typedef:
typedef struct MyStruct MyStruct;
void myfunction2()
{
MyStruct var; /* this is ok now */
struct MyStruct var2; /* this is still ok too */
}
In this second example, var
, and var2
have the same type, although this isn't obvious. Indeed, if the typedef were changed, they would no longer have the same type. Beware of this! It can cause some interesting bugs if type definitions change.
In C++, a struct definition essentially creates an implicit typedef
so that both of the above code snippets compile. There is, in C++, essentially no difference between a struct name (or tag) and a type name. Which is, in my opinion, another great reason to name the two the same way, especially if you anticipate that your C module might be used by some C++ code at some point.