Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct keyword in function parameters, what is the difference?

Tags:

c++

c

struct

I wonder, what is the difference between:

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

and

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

Why do we need struct keyword in second example?

Also, what is the difference between

void Foo(Node* head) 
{
    Node* cur = head;
    //....
}

and

void Foo(struct Node* head) 
{
    struct Node* cur = head;
    //....
}
like image 292
Shay Avatar asked Jul 01 '15 08:07

Shay


People also ask

What does struct keyword do?

'struct' keyword is used to create a structure.

What is the use of struct keyword in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

What's the difference between struct and typedef?

Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.

Do you need struct keyword C++?

Only C++ has added an extra rule that allows to omit the struct (and class ) keyword if there is no ambiguity. If there is ambiguity, also C++ requires the struct keyword in some places. A notorious example is stat on POSIX systems where there is a struct stat and a function stat .


1 Answers

Only the declarations including struct are valid in C. There is no difference in C++.

However, you can typedef the struct in C, so you don’t have to write it every time.

typedef struct Node
{
  int data;
  struct Node *next;  // we have not finished the typedef yet
} SNode;

SNode* cur = head;    // OK to refer the typedef here

This syntax is also valid in C++ for compatibility.

like image 147
Melebius Avatar answered Sep 29 '22 08:09

Melebius