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 typedef
d 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 typedef
d 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 typedef
d 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?