Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the two ways we declared a struct?

Tags:

c++

syntax

As a beginner with C++ I was learning about linked list and other data structures. After looking at a few implementations online I found these two ways they defined struct. What is the difference between the two. In one we add "struct" before the next pointer, and in one we don't.

Way 1:

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

Way 2:

struct node
{
   int data;
   struct node *next;
};
like image 353
Pushkar Mahajan Avatar asked Nov 29 '22 22:11

Pushkar Mahajan


2 Answers

struct node *next;

Is only necessary in C code. In C, doing:

node *next;

Is not allowed. However, in C++, you can use both methods. There is no difference between them in this case.

The only time you would need the struct keyword in C++ for a declaration would be if there is some sort of ambiguity or if the struct has not been defined yet. (An example for the first would the stat function, which is a function and a struct on POSIX systems).

like image 200
Arnav Borborah Avatar answered Dec 05 '22 19:12

Arnav Borborah


What is the difference between the two.

The difference is that the latter (called elaborated type specifier) declares that node is a struct.

In this case, it is redundant to declare that node is a struct, because that has already been declared:

struct node
^^^^^^^^^^^ <-- node is a struct
{
   int data;
   node *next;
};

An example of a case where there is a difference:

struct a {
    //b* pointer;      // oops, we don't know what b is
    struct b* pointer; // OK, b is a struct
};

struct b{};

It is typically not absolutely necessary to use an elaborated type specifier, as it is possible to use a separate declaration instead:

struct b;

struct a {
    b* pointer;
};

struct b{};

Choice between them is personal preference.


I say typically because sometimes you need it to disambiguate a variable of same name from a type:

int foo;
struct foo{};

int main()
{
    foo = 10;            // refers to int
    struct foo instance; // refers to the struct
}

It is usually a bad design to use same name for multiple things, so this is not very typical.


Finally, it is sometimes desirable to write header files that can be included in both C and C++. Such header must use the common subset of both languages.

In C, node is not a type name, but a tag for a structure. It is necessary in C to refer to a struct tag using struct keyword.

like image 39
eerorika Avatar answered Dec 05 '22 19:12

eerorika