0

For example, after I declare a node struct

struct node {
    int data;
    node *next;
}
int main(){
    node *root = new node;
}

I know it would automatically initialize root->data to 0, but what happens to root->next. Is it initialized to nullptr or what?

1 Answers1

1

Neither of those members will be initialized as it stands. If you want them to be set to their "default values" 0 and nullptr respectively, you can use something like this:

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

Now, in every new instance, you will have data == 0 and next == nullptr. This C++11 feature is called "default member initializer".


If you cannot use C++11, you can achieve this value initialization either via

node* root = new node();  // <- Note the parenthesis 

as @vsoftco pointed out or via aggregate initialization like this:

node root = {};

I would however prefer the variant at the top of this post if possible as it yields less opportunity for mistakes.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • 1
    Or you can alternatively (C++98) use `node* root = new node();` This *will* value-initialize the struct. – vsoftco Dec 04 '15 at 21:24