Comp 210 Lab 10: Combining typedef and struct

Here's a generic use of struct and typedef, as we've already seen:
struct galumph_s {
  ...
  };

typedef  struct galumph_s  galumph;
(Remember that there is nothing special about the _s, nor about the similarity between the long name and the short name; we could have equally well said typedef struct galumph_s blazork instead. )

Now for our first trick. The struct definition can actally be incorporated into the typedef. Here's how:

typedef struct galumph_s {
  ...
   } galumph;
Just as before, the type now has two equally valid names: galumph and the long form struct galumph_s. So who would ever use the long name? Nobody. The above can be shortened further by not ever giving the type a long name!
typedef struct {
  ...
   } galumph;
Having done this, there is only one way to refer to this type: just plain old galumph. It is this latest version that you will see used most often, but it helps to know where it came from. Feel free to use whichever makes most sense to you.

Don't be under the impression that typedef is only used in conjunction with structs; this isn't true. (However, the other uses usually are just trying to redress a weakness in C: the inability to define all the types you want to use.)


Back to Lab 10
Back to Comp 210 Home