Okay, let’s jump in the part you already know (or this).
That’s all it is, the structure is anonymous and so you can’t use it directly anywhere that requires it.
I don’t know if you know but it is possible to declare the type of a variable (local or not) or function return like this:
struct Pessoa x;
Or you can do it like this:
struct { char nome[256]; } x;
Obviously this way you can’t take advantage of this definition elsewhere, making the code less DRY and that can be a problem.
And the anonymous form doesn’t allow you to say what structure you want to use on that type, so you can’t take it either. This is only possible because it has a name:
struct Pessoa {
char nome[256];
};
typedef Pessoa Pessoa;
The way with typedef
solves this because the structure is used indirectly and the type is named in some other way:
Pessoa x;
I put in the Github for future reference.
In general where it is possible to define a proper type (in case there may be a definition cycle problem) it does not make much sense to define a name for the struct
.
But there’s a large group of people who think you should define both, just as there are people who think you should write C code as if you were going to run on compilers from the '70s or '80s. I disagree with them for almost all codes, and I disagree more in this case because I have never seen a plausible justification for adopting this pattern. It can exist. I prefer to name the structure only when it is necessary (rare). There is a group that argues that neither the typedef
be used, understand why but disagree in most cases.
There is a difference about the namespace that each identifier is present. With the typedef
the name is global, already with the direct structure the name exists only in the context where the keyword is used struct
, and that’s why both can have the same name being different definitions.
My convention is to use upper case for type names, leaving lower case for variables.
It is more a matter of style, each giving its justification to use one or the other, but changes nothing technically. Some people don’t like abstractions or implicit things.
On Quora I answered something that gives a different example. Other from there.