Given a struct in C defined as follows:
struct Person {
const char *name;
int age;
}
What are the differences between the two declarations below? I was confused when the struct keyword would precede the initialization below:
int main() {
struct Person John = { .name = "John", .age = 10 };
Person Jane = { .name = "Jane", .age = 10 };
return 0;
}
CodePudding user response:
If you define the struct in this way:
struct Person {
const char *name;
int age;
}
Then (1) compiles while (2) does not, since the type of the struct is struct Person
, not Person
. "struct" is required.
// (1)
struct Person John = { .name = "John", .age = 10 };
// (2)
Person Jane = { .name = "Jane", .age = 10 };
However, if you use typedef:
typedef struct person_t {
const char *name;
int age;
} Person;
Then you can use both struct person_t
and Person
as the latter is an alias of the former.