3

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?

Radoslaw Krasimirow
  • 1,833
  • 2
  • 18
  • 28
  • See http://stackoverflow.com/questions/2091499/why-global-and-static-variables-are-initialized-to-their-default-values for more information – derhoch May 04 '15 at 11:57

2 Answers2

3

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.

Community
  • 1
  • 1
Victor Dodon
  • 1,796
  • 3
  • 18
  • 27
2

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.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57
  • Aren't the static variables global variables as well? I know that the global variables are initialized to 0? – Radoslaw Krasimirow May 04 '15 at 09:22
  • static variables can appear inside a function, and yes, as global variables in the module (though invisible for the rest of the modules). I wouldn't trust any programing language to initialize my variables for me, no matter their storage. You can see this another question: http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program – Baltasarq May 04 '15 at 10:14