Search code examples
ccompiler-constructionlanguage-design

Why do C programs keep saying 'struct' every time they refer to one?


Though I rarely write C code, I often see it (mostly due to books in my field having it as sort of reference language for algorithm examples) and something has been bugging me for a while about the way variables/parameters are declared. The best example would be this List with a twist example, about a particular implementation of Linked List used in Linux kernel (sorry, I had a link to a blog post originally, but apparently the blog post has been deleted, I copied code from my browser's cache).

struct blog {
  ...
  struct ls posts;
};

struct post {
  ...
  struct ls blog_posts;
};

void delete_blog(struct blog *blog) {
  ...
  struct post *p;
  ls_for_each(&blog->posts, p, blog_posts) {
    free(p);
  }
  free(blog);
}

What bugs me is the fact that they keep repeating the keyword struct everywhere. I mean things like ls, blog, post are declared as structs, so what is the point of saying it is a struct every time you declare a variable or a function parameter of that type? What does this tell the compiler that it can't infer from the fact that the thing you are instantiated has been defined as a struct?


Solution

  • Well, it's because if there isn't a typedef, that's the only way to refer to the struct.

    In C, if you have:

    struct thing {
      // stuff here
    };
    

    and you want to have a variable of that type, you need to either:

    • use struct thing as the type specifier
    • make a typedef like typedef struct thing thing_t; and use thing_t as the type specifier.

    (C++ is different in this respect.)