开发者

Why are all of the elements of a structure initlized to 0 when we just initlize 1 member out of 3 for example

开发者 https://www.devze.com 2023-02-12 22:51 出处:网络
For Example: typedef struct student { int rollno;开发者_开发百科 float cgpa; char name[20]; }Student;

For Example:

typedef struct student { 

     int rollno;开发者_开发百科
     float cgpa;
     char name[20];

}Student;

Student me= {0,0}; // will intilize name with all zeros


That's the way it is. This is the standard expected behavior. The same is with arrays. E.g.

int a[3] = {1}; // a is {1, 0, 0}
int a[3];       // a is {undefined, undefined, undefined}    

As to what was the rationale, I think it was to keep the struct either initialized completely or not at all... maybe :)


A common misunderstanding is that Something x = {0}; should initialize all members to the same value.

The C standard states that if all of the elements in an "aggregate" (arrays, structs etc) are not initialized explicitly, then the remaining values should be initialized as if they had static storage duration.

And all elements that have static storage duration, ie those declared with keyword static and all global variables, must be initialized to zero if the programmer didn't initialize them explicitly.

So in your example, "rollno" and "cgpa" are initialized explicitly, to zero in this case, and the rest of the struct is initialized as if it had static storage duration, meaning it will be zero as well.


Once you initialized a single field of a struct, the whole variable goes to a section with all other initialized values. So all field are initialized, because that section is implemented in the executable as a byte array.

Regarding the value being 0, I guess that it is because 0 has more chance to raise an exception when a variable is used uninitialized. Think divide by zero or NULL pointer exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号