I wonder, what is the difference between:
struct Node
{
int data;
Node *next;
};
and
struct Node
{
int data;
struct Node *next;
};
Why do we need struct
keyword in second example?
Also, what is the difference between
void Foo(Node* head)
{
Node* cur = head;
//....
}
and
void Foo(struct Node* head)
{
struct Node* cur = head;
//....
}
'struct' keyword is used to create a structure.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.
Only C++ has added an extra rule that allows to omit the struct (and class ) keyword if there is no ambiguity. If there is ambiguity, also C++ requires the struct keyword in some places. A notorious example is stat on POSIX systems where there is a struct stat and a function stat .
Only the declarations including struct
are valid in C. There is no difference in C++.
However, you can typedef
the struct
in C, so you don’t have to write it every time.
typedef struct Node
{
int data;
struct Node *next; // we have not finished the typedef yet
} SNode;
SNode* cur = head; // OK to refer the typedef here
This syntax is also valid in C++ for compatibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With