Reputation: 1
Got confuse of a C++ code snippet when I study C++, Could someone help me on this? Thanks In advance.
struct LinkNode
{
int data;
struct LinkNode* next; // Why there use `struct` type define LinkNode again?
};
As my comments, why there use struct
type define LinkNode again? I think code struct LinkNode{}
had already define a LinkNode. Of course, if I change the code as below, it works fine without any compilation error either.
struct LinkNode
{
int data;
LinkNode* next; // No any compilation errors either.
};
Upvotes: 0
Views: 254
Reputation: 54737
In the code
struct LinkNode
{
int data;
struct LinkNode* next; // Why there use `struct` type define LinkNode again?
};
The line struct LinkNode* next;
does not define a new type. It declares a member variable next
of the (already existing) type LinkNode
.
What threw you off here is probably the keyword struct
, which, as you already figured out, is purely optional in this context. The reason why you are allowed to put struct
here in the first place is a heritage from C. C distinguishes between tag names and type names. A declaration of the form struct Foo {};
in C only introduces a tag name Foo
, but not a type name. This means that to instantiate an object of Foo
in C you would need to write struct Foo f;
, with the struct
keyword there to turn the tag name into the corresponding type.
To get a proper type name in C, you'd have to use a typedef: typedef struct Foo FooType;
which would then allow you to just write FooType f;
. Since this distinction between tag names and type names proved to be not very useful in practice, C++ simply got rid of the distinction, allowing the simpler declaration notation you are familiar with.
Upvotes: 1
Reputation: 238461
Type Redefinition of Struct In C++?
This is not a type redefinition. This is called an elaborated type specifier. It can be used to disambiguate a class name from another name that hides it. It is not necessary to use it in this case. It also doesn't break anything to use it.
The code may be written for an API usable from C as well. In C, this is necessary.
Upvotes: 1