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

As a newbie with C ++, I studied a linked list and other data structures. After exploring several implementations on the Internet, I found these two ways of defining structure. What is the difference between the two. In one, we add "struct" before the next pointer, and in one we do not.

Method 1:

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

Method 2:

struct node
{
   int data;
   struct node *next;
};
+4
source share
6 answers
struct node *next;

Only required in C code. In C, doing:

node *next;

Is not allowed. However, in C ++ you can use both methods. In this case, there is no difference between the two.

, struct ++ , , - struct . ( stat, struct POSIX).

+9

.

, ( ) , node .

, node , :

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

, :

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

struct b{};

† , :

struct b;

struct a {
    b* pointer;
};

struct b{};

- .


† , , :

int foo;
struct foo{};

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

, , .


, , C, ++. .

C, node , . C struct struct.

+8

C, ++, ++ , , .

, ++, . std::list std::forward_list.

+3

. :

struct foo { struct node* f; };   // <- this is fine
struct foo_broken { node* f; };   // <- wont compile

struct node { };

int main() {
    foo f;
    //foo_broken g;
}

struct , node. struct ( foo_broken):

error: β€˜node’ does not name a type

, struct . foo, node, foo.

+1

, ++ C C, , struct . , , // .. , . , ++, C ++ .

C struct . , β„– 2: C:

struct node
{
    int data;
    node *next; //error in C!
};

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

C, struct typedef , :

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

node struct . ++ typedef struct class , struct class .

+1

++

0

Source: https://habr.com/ru/post/1693743/


All Articles