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.

5
  • 2
    Yeah you don't need to say struct in C++ Commented Feb 1, 2017 at 19:21
  • 2
    This is a C thing. In C one often uses a typedef to avoid that, but in C++ you can always use the type without the struct or class keyword. Commented Feb 1, 2017 at 19:21
  • Ahh , That would explain why we use typedef struct in Objective C Commented Feb 1, 2017 at 19:23
  • 2
    Don't forget the semicolon after the struct definition though, I don't think your code will compile as is. Commented Feb 1, 2017 at 19:24
  • The word is not redeclared, it's there because you name a struct by its tag. And some would say that's preferable. Commented Feb 1, 2017 at 19:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

9 Comments

You most certainly should do this in new code, if that code is a C binding.
The question is tagged C++ so what C does bears no relevance for writing new C++
And new C binding are no longer written for C++ libraries? That's news to me.
StroryTeller - That's good info moving forward. I'll just get in the habit of using typedef struct.
@Miek - Don't. It's not required for C++. And as discussed in the thread I linked to your question, it can actually make the C bindings better.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.