Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between struct Data d = {0} and struct Data d = {}

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.

like image 216
vikas Avatar asked Nov 23 '16 06:11

vikas


People also ask

How to initialise a struct in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.

What does struct mean in C++?

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.).

How do you initialize a structure?

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 ( = ).

Do structs have methods?

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 .


1 Answers

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 members and bases (since C++17) are initialized by 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.

like image 111
songyuanyao Avatar answered Nov 11 '22 15:11

songyuanyao