Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are uninitialized struct members always set to zero?

Tags:

c++

c

Consider a C struct:

struct T {     int x;     int y; }; 

When this is partially initialized as in

struct T t = {42}; 

is t.y guaranteed to be 0 or is this an implementation decision of the compiler?

like image 424
VoidPointer Avatar asked Apr 01 '09 15:04

VoidPointer


People also ask

Is struct initialized to 0?

If a structure variable does not have an initializer, the initial values of the structure members depend on the storage class associated with the structure variable: If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type.

How do you know if a struct is uninitialized?

The only way you could determine if a struct was initialized would be to check each element within it to see if it matched what you considered an initialized value for that element should be.

Are global structs initialized to 0?

Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).

What is the default value of an uninitialized variable?

INTRODUCTION: An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using.


2 Answers

It's guaranteed to be 0 if it's partially initialized, just like array initializers. If it's uninitialized, it'll be unknown.

struct T t; // t.x, t.y will NOT be initialized to 0 (not guaranteed to)  struct T t = {42}; // t.y will be initialized to 0. 

Similarly:

int x[10]; // Won't be initialized.  int x[10] = {1}; // initialized to {1,0,0,...} 

Sample:

// a.c struct T { int x, y }; extern void f(void*); void partialInitialization() {   struct T t = {42};   f(&t); } void noInitialization() {   struct T t;   f(&t); }  // Compile with: gcc -O2 -S a.c  // a.s:  ; ... partialInitialzation: ; ... ; movl $0, -4(%ebp)     ;;;; initializes t.y to 0. ; movl $42, -8(%ebp) ; ... noInitialization: ; ... ; Nothing related to initialization. It just allocates memory on stack. 
like image 183
mmx Avatar answered Oct 05 '22 11:10

mmx


item 8.5.1.7 of standard draft:

-7- If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized (dcl.init). [Example:

struct S { int a; char* b; int c; }; S ss = { 1, "asdf" }; 

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]

like image 26
bayda Avatar answered Oct 05 '22 11:10

bayda