Reputation: 35
So, basically I want to know what is the difference (if there is any) between these two notations:
First example:
struct Node{
int data;
Node* next;
};
Node* head;
Second example:
struct Node{
int data;
struct Node* next;
}
struct Node* head;
I just want to know what's the difference between these two notations, and which is better two use?
Upvotes: 0
Views: 80
Reputation: 238311
I want to know what is the difference (if there is any) between these two notations
Node
is a type name of a class. It can be used only if the class has been declared. Example:
Node* ptr; // won't work without prior declaration
struct Node;
struct Node;
Node* ptr; // works because of prior declaration
struct Node
is the same type name using elaborated type specifier. It is declaration of the class by itself. Example:
struct Node* ptr; // works without prior declaration
Elaborated type specifier can be used to disambiguate when a function and a class have the same name:
struct Node;
void Node();
void foo() {
Node* ptr; // this won't work
struct Node* ptr; // this works
Node(); // this is a function call
}
Given that in your example the class has already been declared, and there is no ambiguous function, there is no difference other than struct Node
is about 64% longer to type.
which is better two use?
Which ever you prefer. Do you like to type more or to type less?
Note about C language: In C, structs do not get a type name automatically, so they can only be referred to using an elaborated type specifier unless the struct has explicitly been given a type name using typedef
. This is why you may see elaborated type specifiers used more commonly in C than in C++, as well as typedefs that would be redundant in C++.
Upvotes: 1