structure naming syntax

I am looking at a linked list example, which uses structs:

1
2
3
4
typedef struct node {
    int val;
    struct node * next;
} node_t;


As you can see, we provide an optional name "node" that follows the word struct. And we can use "node" subsequently as a shorthand for the part of the declaration in braces.

But what is that node_t for? What is that doing?
node_t is the resultant data type. So you can declare variable of type node_t like node_t *root

But this is C way of declaring a struct C++ way is

1
2
3
4
struct node_t {
    int val;
    node_t *next;
};

Let's just confirm something, in C, when I do this:

node_t *root

that gets translated to:

1
2
3
4
struct root {
    int val;
    struct node * next;
} 


?
No. What you've posted would define a struct type called root.

node_t *root

creates a variable called root, whose type is a pointer to a struct node.
You have to look at this from the outside in.

The first statement you see is typedef <some type> node_t; This tells you that <some type> is being given an alias of node_t. That means that any time node_t is used in the code, it will refer to <some type>.

Before the alias can be assigned, the compiler has to first determine what the original type is that is being typedefed. Now we have to look at what <some type> is.

1
2
3
4
struct node {
    int val;
    struct node * next;
}


This is a named struct containing an int and a pointer to another one its own type. Because this struct is being defined before the definition of node_t is completed, the node_t alias cannot be used for the next pointer type. As a result, the full type name "struct node" must be used to define the type of the next pointer.

In C++ this no longer needs to be done. Because of different namespace handling in C++, we no longer need to specify "struct" when using a struct variable or pointer.

1
2
3
4
5
6
struct ABC
{
    int a;
    int b;
    int c;
};


C syntax:
1
2
struct ABC var1;
struct ABC *ptr = &var1;


C++ syntax:
1
2
ABC var1;
ABC *ptr = &var1;
javascript:editbox1.editPreview()

The typedef in C allowed C syntax to look more like C++ syntax before C++ existed.
Topic archived. No new replies allowed.