Case 1
struct{
int edad;
char *ptr;
}hola;
Here you are declaring a variable called hola
that is based on an anonymous structure. Note that you will not be able to create more variables based on this structure since it has no name.
Case 2
struct hola{
int edad;
char *ptr;
}holas;
Here, instead, you create a structure named hola
and then declare a variable called holas
based on that structure. By having, in this case, a name the structure, you can create new variables based on this structure when you need it:
struct hola otraVariable;
Which option is better? It depends on your needs. In any case, it is not a good idea to go around declaring global variables with joy, so your examples do not follow precisely good practices.
On the other hand, declare the variable at the same time that the structure can lead to less readable code. My experience is that it is usually advisable to separate the declaration of the structure from the declaration of variables:
struct hola
{
/* ... */
};
struct hola unaVariable;
To make the declaration of variables based on structures less cumbersome we can resort to the use of typedef
. As you can see in the following two examples, the simple fact of using typedef
modifies the behavior of the program since they will not be able to declare structures and variables at the same time, so this is another point in favor to avoid confusion.
Case 1 (with typedef)
typedef struct{
int edad;
char *ptr;
}hola;
In this first case we are creating an anonymous structure and then we assign an alias to said structure (Note that variables are no longer declared here). Despite being an anonymous structure, the fact of having an alias will allow us to declare variables based on this structure in any part of the code:
hola unaVariable;
Case 2 (with typedef)
The following example, instead:
typedef struct holas{
int edad;
char *ptr;
}hola;
Declares a structure named holas
and then assigns it an alias called hola
. In this case we will have two different ways to declare variables:
struct holas unaVariable;
hola otraVariable;