I have two types of structure variable initialization in my code.
Example
#include<iostream>
#include<string>
using namespace std;
struct Data{
int arr[5];
float x;
};
int main(){
struct Data d = {0};
struct Data d1 = {};
cout<<d.arr[0]<<d.x;
cout<<d1.arr[0]<<d1.x<<endl;
return 0;
}
I am running the code ad getting 0 0 0 0 as my output. Please help me, is there any difference between both initialization.
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
Contrary to what younger developers, or people coming from C believe at first, a struct can have constructors, methods (even virtual ones), public, private and protected members, use inheritance, be templated… just like a class .
According to the rule of aggregate initialization, the effect is the same here, i.e. all the members of the struct will be value-initialized (zero-initialized here for non-class types).
If the number of initializer clauses is less than the number of members
and bases (since C++17)
or initializer list is completely empty, the remaining membersand bases (since C++17)
are initializedby their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.
More precisely,
struct Data d = {0}; // initialize the 1st member of Data to 0, value-initialize(zero-initialize) the remaining members
struct Data d1 = {}; // value-initialize(zero-initialize) all the members of Data
Note that the whole story is based on that Data
is an aggregate type and its members are non-class types, otherwise the behavior would change according to the rule of list initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With