0

Quick Question about passing a struct as a function arg. Maybe its a carry over from C that makes no difference in C++.

In many Linked List examples you see them re-declare the word struct in any function argument that takes a struct and I don't understand why. Or any allocation for that matter. A structure is its own object and declaring just the name of the struct is sufficient.

Example:

struct Node{

    int data;
    Node * next;
};

// Function to output data.
void printNode(struct Node* myNode){ 

    // Print data of node

}

why is the word struct re-declared in the function arg. Declaring type Node* works just fine.

Thanks.

Miek
  • 1,127
  • 4
  • 20
  • 35

2 Answers2

7

There is a difference between C and C++ use of declarations produced with struct keyword:

  • In C, struct defines a new struct tag, but not a new type
  • In C++, struct defines a new type.

The consequence is that C++ lets you use the name defined in struct, while C requires you to either prefix a struct to the tag, or use typedef to define a new type.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

C requires it. C++ does not require it, but allows it for backward compatibility. Do not do this for new code.

Rob K
  • 8,757
  • 2
  • 32
  • 36