RedLars said:
From what I understand this is declaration of a struct;
struct person
{
char * first;
char *last;
int age;
};
The unqualified phrase "a struct" can be ambiguous; it can refer
either to a struct type or to an object (variable) of a struct type.
The above declares a struct type called "struct person".
And to use this type (allocate memory);
struct person p;
Right, that declares (and defines) an object of type "struct person".
What about this bit of code;
struct
{
char * first;
char *last;
int age;
} person;
Is this equivalent to the first example? If not, what is the
difference?
In your first example, the type is named "struct person" and the
object is named "p". In your second example, the type has no name
(which is bad if you ever want more than one object) and the object is
named "person". Other than that, they're equivalent.
By adding 'typedef' infront of both these code blocks;
typedef struct person {...};
That's invalid; what you want is
typedef struct person {...} person;
The first "person" is the struct tag; the second is the typedef name.
You can use the same identifier for both, since a struct tag always
immediately follows the keyword "struct".
typedef struct {...} person;
Here the struct has no tag (which is ok); its only name is the typedef
name "person".
What does that accomplish? Have read in a tutorial that you dont have
to write;
struct person p;
but can instead write;
person p;
Is that the only difference? It doesnt change the scope of the
variable or anything else behind the scenes? Just makes the code
easier to read.
A typedef creates an alias for an existing type. That's *all* it
does.
There's a (mostly good-natured) controversy about whether typedefs for
structs are a good idea.
The argument against them is that the type already has a perfectly
good name, and defining an alias doesn't buy you anything; you can
just refer to it everywhere as "struct person" This is more explicit;
the code that uses the type needs to know that it's a struct type
anyway. (The exception is when it's truly an abstract type whose
innards should be hidden from code that uses it; FILE is an example of
this.)
On the other hand, a typedef for a struct does give you a one-word
name for the type, and plenty of programmers feel that this
convenience is worthwhile. <OT>Note that C++ lets you refer to
"struct person" as just "person"; a typedef lets you do the same thing
in C.</OT>
Note that the typedef name isn't available until the end of the
declaration, so you generally have to use the struct tag within the
struct declaration itself:
typedef struct person {
char *name;
struct person *father;
struct person *mother;
} person;
person you;
There are more issues I haven't gone into (whether the typedef name
really should be the same as the struct tag, and if not, how they
should be related; whether the typedef and struct should be declared
together or in separate declarations; and so forth).