Denis Golovkin Denis Golovkin - 11 months ago 65
C Question

c cyntax typedef struct explanation

In following example:

typedef struct Books {
char title[50];
char author[50];
int book_id;
} Book;

can be used then, to declare variable, like:

Book myBook;

But what the meaning of
? How it can be used, or why we need it ?
I interested mostly in plain c, but if you can explain about c++ as well it will be great.


To be more specific, what the difference between code above and following code:

typedef struct {
char title[50];
char author[50];
int book_id;
} Book;

Why we ever need an extra literal in first example?

Found good explanation here:
Tag vs. Type Names in C and C++

Answer Source

The typedef says that Book is an alias for struct Books. Anywhere you use one, you can use the other.

The only exception is if struct Books contains a pointer to another struct Books. In that case, you can't use the alias.


You can do the above if you use a forward declaration:

typedef struct Books Book;

struct Books {
   Book *moreBooks;

As for Books, that by itself is not a valid type. You need to prefix it with the struct keyword. This differs from C++ where the struct (or class) keyword is optional when referencing it.


In the second code sample you give, Book is an alias for an anonymous struct. In that case, the alias must be used to reference it.