Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the members of a global structure initialized to zero by default in C?

Tags:

Are the members of a global or static structure in C guaranteed to be automatically initialized to zero, in the same way that uninitialized global or static variables are?

like image 410
tkw954 Avatar asked Nov 02 '10 18:11

tkw954


People also ask

Are global variables initialized to zero in C?

Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.

Are global variables always initialized to 0?

Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.

Does C initialize struct to 0?

You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.

What is default value of global variable in C?

Thus global and static variables have '0' as their default values. Whereas auto variables are stored on the stack, and they do not have a fixed memory location.


1 Answers

From the C99 standard 6.7.8/10 "Initialization":

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules

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

The C++ 2003 standard has a similar requirement (3.6.2 "Initialization of non-local objects"):

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.

Sometime after that zero-initialization takes place, constructors are called (if the object has a constructor) under the somewhat more complicated rules that govern the timing and ordering of those calls.

like image 171
Michael Burr Avatar answered Oct 21 '22 16:10

Michael Burr