user5498197
user5498197

Reputation:

Questions about Structure definitions

I am new to c, I have a question about structures (see the next code):

typedef struct student{
  char name[20];
  int grade;
} student1;

typedef struct group_project{
  char name_of_group[20];
  struct group_project *next;  // points to the next group
  student1 *student1;           //head of the group
} group_project;
  1. What is the difference between student and student1 (what is the name of the struct?). Can you use the same name?
  2. Why do you need to add "struct" when using group_project but you dont add struct when using the student struct?
  3. Can you use a structure without "typedef"?

Upvotes: 0

Views: 87

Answers (2)

What is the difference between student and student1 (what is the name of the struct?). Can you use the same name?

student is the structure tag or the "name" of the structure itself and student1 is an typedefd alias of type struct student. Yes, they can have the same name or identifier because they reside in different name spaces.

Why do you need to add "struct" when using group_project but you don´t add struct when using the student1 structure?

In C, as opposed to C++, when you define an object of a structure, and didn´t typedefd the structure or defined the object at the declaration of the structure itself, you have to precede the structure tag by the keyword struct at the declaration of the respective object, like for example:

struct student student_x;         // `struct` keyword required.

Since student1 is already typedefd before, at the declaration of the structure student, you don´t need to use the struct keyword anymore, when you defining an object of that structure type.

As opposed to that, group_project as type of the pointer next in the project_group structure needs to be preceded by the keyword struct because the typedef of group_project is defined thereafter in the source code and isn´t valid at this point of time inside the structure.

Can you use a structure without "typedef"?

Yes, of course. Some user amongst the community even say this is even more appreciated because it makes your code more readable. I recommend to always use the structure by itself and not blending with any typedef, even if it requires a little bit more key typing, just to keep your code a little bit clearer, but this is a matter of opinion and style. Here you can make you your own image of it:

typedef struct vs struct definitions

Why should we typedef a struct so often in C?

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

student1 is an alias for the type struct student.

And inside the group_project structure the type-alias group_project doesn't exist yet, so you have to use struct group_project.

And in C you can't use the structure tag name (like e.g. student) without the keyword struct. The whole type is struct student.

Upvotes: 3

Related Questions