In C++, if you declare a struct
, union
, or enum
, its name is immediately accessible without any qualifiers:
struct foo { ... };
foo x; // declare variable
In C, this won't work, because types thus declared live in their own distinct namespaces. Thus, you have to write:
struct foo { ... };
struct foo x; // declare variable
Notice the presence of struct
there on the second line. You have to do the same for union
and enum
(using their respective keywords), or use the typedef
trick:
typedef struct { ... } foo;
foo x; // declare variable
Consequently, you can have several types of different kinds named the same in C, since you can disambiguate:
struct foo { ... };
typedef enum { ... } foo;
struct foo x;
foo y;
In C++, however, while you can prefix a struct
name with keyword struct
whenever you reference it, the namespaces are merged, and so the above C snippet isn't valid. On the other hand, C++ specifically makes an exception to allow a type and a typedef for that type to have the same name (obviously with no effect), to allow the use of typedef
trick unchanged from C.