8

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;
    //....
}
Shay
  • 131
  • 5

2 Answers2

5

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.

Melebius
  • 6,183
  • 4
  • 39
  • 52
  • 5
    *"There is no difference in C++."* - that's not quite true... with `struct Node* next;` is only searches for a `struct`/`class`/`union` by that name and happily ignores non-`struct`/`class`/`union`s with the same identifier. For example, if you add an `int Node;` data member to `struct Node;`, it won't conflict with `struct Node* next;` but will conflict with `Node* next;`. Nobody sane relies on this distinction though - makes for unmaintainable code. – Tony Delroy Jul 01 '15 at 09:15
0

Struct node is a new user defined datatype that we create. And unlike classes the new data type using structures is "struct strct_name" , ie; u need the keyword struct in front of the struct_name. For classes u do not need keywords in front of the new data type name. eg;

class abc
{
  abc *next;
};

and when u declare variables

abc x;

instead of struct

abc x;

in case of structures . Also understand that by the statement

struct node * next;

we are trying to create a pointer that points to a variable of type "strcut node", which is called a self referential pointer in this case since it points to the parent structure.