Radoslaw Krasimirow
Radoslaw Krasimirow

Reputation: 1873

Elements of a static structure

I would like to ask you: Are the elements of static structure initialized to zero? For example:

static struct _radioSettings
{
   unsigned char radio_in;
   unsigned char radio_out;
}radioSettings;

So this structure is placed in module radio-settings.c If radioSettings.radio_in and radioSettings.radio_out are not initialized to zero at compilation how can I initialize them inside the module radio-settings.c?

Upvotes: 3

Views: 109

Answers (2)

Victor Dodon
Victor Dodon

Reputation: 1874

All global variables are initialized to the default values.

Section 6.7.8 Initialization of C99 standard (n1256) says:

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.

So for your structure, each field is initialized to its default value, that is 0.

Upvotes: 3

Baltasarq
Baltasarq

Reputation: 12212

Static, in C, is related to the visibility of the structure, it does not mean anything else than it is not visible from outside module radio-settings.c.

Structures in C are not initialized to anything. The values for its fields are the memory values the structure landed in. So, you cannot count on anything like that.

If you want to initialize the structure, then it is simple:

memset( &radioSettings, 0, sizeof( _radioSettings ) );

You only have to place that in an init() function for the radioSettings, inside the module radio-settings.c

Hope this helps.

Upvotes: 2

Related Questions