1

What's the difference between:

  struct name{
    int example;
    name *next;
    };

struct name *next= NULL;

...and

name *next=NULL;`

(defined after the data structure, when the linked list is still empty) ?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

2

"What's the difference between ..."

There's none. The struct or class keyword is optional in pointer declarations.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

First of all the data member with name next in the structure

struct name
{
    int example;
    name *next;
};

and variable with the same name declared after the structure as for example

struct name *next = NULL;

are two different entities.

The last declaration does not initialize to NULL the data member of any object of the structure. It declares a pointer to an object of the type of the structure.

Now about the difference between the two declarations

struct name *next = NULL;

and

name *next = NULL;

In the first one there is used so-called elaborated type name struct name. Its advantage compared with the second declaration is that any object, enumerator or a function that declared with the same name name hide the declaration of the structure. For example

struct name
{
    int example;
    name *next;
};

enum { name, noname };

Here enumerator name hides data type struct name and if you write for example

name *next = NULL;

then the compiler will issue an error.

But if you will use the elaborated name

struct name *next = NULL;

then the code compiles successfully because the compiler now knows that name in this declaration is struct name.

Another important difference.

Consider the following code snippet

int main()
{
    struct name
    {
        int example;
        name *next;
    };

    {
        name *next = NULL;
    }
}

In this progam the declaration within the inner code block declares a pointer of type of the struture declared in the outer code block.

Now rewrite the program

int main()
{
    struct name
    {
        int example;
        name *next;
    };

    {
        struct name *next = NULL;
    }
}

In this case the declaration in the inner code block introduces a new type struct name that hides the structure declaration in the outer code block.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335