struct book
is the type name (like int
or double
). The type is being defined by the stuff between the curly braces - { char title[50]; int year; }
. In the first snippet, boo
is being declared as an object (variable) of type struct book
.
C allows you to both define the struct type and declare objects of that type in the same declaration. It may make sense to see the two operations broken up:
struct book { char title[50]; int year; }; // creates the *type* "struct book"
struct book boo; // declares a *variable* of type "struct book"
The typedef
facility allows you to create synonyms or aliases for a type - in this case, typedef struct book { char title[50]; int year; } boo;
creates boo
as a synonym for struct book
. You can then create objects as
boo b1; // b1 is type boo, which is a synonym for struct book.
Again, it may help to split things up:
struct book { char title[50]; int year; }; // creates the type "struct book"
typedef struct book boo; // makes boo an alias for type "struct book"
In struct book
, book
is the tag name for the struct type - it's what allows you to refer to that type after you've defined it, like
struct book b2;
void some_function( struct book b );
etc.
If you write something like
struct { char title[50]; int year; } boo;
then only boo
can have that type - you can't declare other variables of that same type, because there's no way to refer to it anymore. Even if you repeat the type:
struct { char title[50]; int year; } boo;
struct { char title[50]; int year; } b2;
boo
and b2
technically have different types, even though the type implementations are identical.
Now, if you use the typedef facility, you can omit the tag name:
typedef struct { char title[50]; int year } boo;
because now you refer to that type with the typedef
name boo
:
boo b2;
void some_function( boo b );