In C if I declare a struct/union/enum:
struct Foo { int i ... }
when I want to use my structure I need to specify the tag:
struct Foo foo;
To loose this requirement, I have to alias my structure using typedef:
typedef struct Foo Foo;
Why not have all types/structs/whatever in the same "namespace" by default? What is the rationale behind the decision of requiring the declaration tag at each variable declaration (unless typdefe'd) ???
Many other languages do not make this distinction, and it seems that it's only bringing an extra level of complexity IMHO.
In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.
C has four different name spaces for identifiers: Label names (the goto type). Tags (names of structures, unions and enumerations). Members of structures and unions (these have a separate namespace per structure/union). All other identifiers (function names, object names, type(def) names, enumeration constants, etc).
Structures/records were a very early pre-C addition to B, just after Dennis Ritchie added a the basic 'typed' structure. I believe that the original struct
syntax did not have a tag at all, for every variable you made an anonymous struct
:
struct {
int i;
char a[5];
} s;
Later, the tag was added to enable reuse of structure layout, but it wasn't really regarded as real 'type'. Also, removing the struct
/union
would make parsing impossible:
/* is Foo a union or a struct? */
Foo { int i; double x; };
Foo s;
or break the 'declaration syntax mimics expression syntax' paradigm that is so fundamental to C.
I suspect that typedef
was added much later, possible a few years after the 'birth' of C.
The argument "C was the highest level language at the time." does not seem true. Algol-68 predates it and has records as proper types. The same holds for Pascal.
If you like to know more about the history of C you might find Ritchie's "The Development of the C Language" an interesting read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With