How do I initialize all C++ structure member variables to zero?

Asked 2 years ago, Updated 2 years ago, 97 views

Is there an easier way to initialize all object member variables to zero? Now

struct Snapshot
{
    double x; 
    int   y ;
};

int main(){
    struct Snapshot mystruct;
    mystruct.x = 0;
    mystruct.y = 0;
}

They're resetting everything How do I initialize x,y to zero immediately when I first declare it?

c c++ struct zero-initialization

2022-09-21 16:22

1 Answers

There are so many ways to initialize a structure at the same time as a declaration. I'll show you several examples, so look at the notes in the code

Snapshots; // Declare without initialization
Snapshots = {}; // initialize all members - all set to 0

The initialization method is the same even if the member is not a basic type such as int or long, but a structure comes.

structure Parent { Snapshots; }; //Have Snapshot as a member
Parent p; // Declare without initialization
Parent p = {}; // initialize all members - {x,y} set to zero

If you want to initialize to a value of zero or something else, Or, if you have an array that you want to dynamically assign as a member, You can create a constructor and initialize it as soon as it is created.

struct Snapshot {
    int x;
    double y;
    int *myarr;
    Snapshot():x(0),y(0) //x, constructor that initializes 0 to y
    {
        myarr = new int[30];
    }
};


2022-09-21 16:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.