I have seen many programs consisting of structures like the one below
typedef struct { int i; char k; } elem; elem user;
Why is it needed so often? Any specific reason or applicable area?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As Greg Hewgill said, the typedef means you no longer have to write
structall over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.Stuff like
becomes cleaner when you don’t need to see the ‘struct’ keyword all over the place, it looks more as if there really is a type called ‘Point’ in your language. Which, after the
typedef, is the case I guess.Also note that while your example (and mine) omitted naming the
structitself, actually naming it is also useful for when you want to provide an opaque type. Then you’d have code like this in the header, for instance:and then provide the
structdefinition in the implementation file:In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of
typedefto hidestructis considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus’ angry words. 🙂 My point is that the ‘should’ in the question is perhaps not set in stone, after all.