Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the first "node" in the declaration: "typedef struct node { - - - } Node;"?

Tags:

c

I am studying code examples from my professor in order to become better acquainted with linked data structures.

In our linked-list.c example the professor defines a type Node as follows:

typedef struct node {
  int data;
  struct node *next;
} Node;

What's the point of the lower case node? I was under the impression that you could just write, for example:

typedef struct {
  int data;
  struct node *next;
} Node;

and then use Node as its own type. Does it have something to do with the fact that if you don't include a lower case node then when the compiler is evaluating the code it will not be able to understand what is meant by "struct node *next"?

like image 520
Herald D. Precursor Avatar asked Mar 20 '13 18:03

Herald D. Precursor


2 Answers

Does it have something to do with the fact that if you don't include a lower case node then when the compiler is evaluating the code it will not be able to understand what is meant by "struct node *next"?

Yes.

The node in struct node is the tag of the struct type. If you give the struct a tag, you can refer to that type from the moment on the tag is complete, so in

typedef struct node {
  int data;
  struct node *next;
} Node;

the struct node *next; declares a member next that is a pointer to the struct type being defined. The typedef name Node is not available before the ; ending the definition is reached.

If you omit the tag, you cannot refer to the type being defined in any way before the typedef is complete, so in

typedef struct {
  int data;
  struct node *next;
} Node;

the line struct node *next; declares a new, unrelated, incomplete struct type with the tag node that next points to.

That's valid, but nothing about struct node is known (unless it is defined somewhere else), so you can't use the next pointer without casting it to a pointer to a complete type everywhere (not quite everywhere, Node foo; foo.next = malloc(12); etc. would still work).

like image 126
Daniel Fischer Avatar answered Oct 05 '22 23:10

Daniel Fischer


He is defining a temporary name for the node because he is using a well know technique to avoid writing struct node on the declaration of each struct object.

If he would just do:

struct node {
  int data;
  struct node *next;
};

you would have had to use:

struct node* node;

to declare a new node. And to avoid that you would have to define later:

typedef struct node Node;

in order to be able to declare objects like the following:

Node* node;

In the end:

typedef struct node {
  int data;
  struct node *next;
} Node;

Is just a shortcut for struct node { ... }; in addition to typedef struct node Node;.

like image 34
Shoe Avatar answered Oct 05 '22 23:10

Shoe