1

I was trying to make a tree in c++ and came across this code which is really confusing me.

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

// The code bellow this is the part i dont understand
struct node* newNode(int idata)
{
    node* node = new struct node;
    node->data = idata;
    node->left = NULL;
    node->right = NULL;
    return node;
}

what is struct node* ? Some kind of a structure, but a pointer? Also shouldn't structs have ; at the end? For example, node has ; at the end of the body but not node* ?

  • 5
    It's C syntax. You can remove the keyword `struct` in C++. – Ted Klein Bergman Nov 15 '20 at 20:31
  • 2
    `newNode` is a function that takes an `int` and returns a `node*` pointer. Here `struct node` is the same as `node` - the redundant `struct` keyword is a remnant of C language, almost never needed in C++. For further details, see [elaborated type specifier](https://en.cppreference.com/w/cpp/language/elaborated_type_specifier) – Igor Tandetnik Nov 15 '20 at 20:32

1 Answers1

0

struct node* is the return type of function newNode() and not a definition in itself. The line you are referring to is the signature of the function newNode. It is followed by the function definition between the two curly braces {}. A function definition does not need a ; at the end.

nvjsingh
  • 1
  • 2