0

I've noticed that inside a library of STM32, there is a piece of the code which initialize a stucture variable with {0}. Below is a simplified example:

   typedef struct
    {
        uint16_t           val_a;  
        uint16_t           val_b;
        uint16_t           val_c;
    } dataset_t;
dataset_t Dataset = {0};

The goal of this code is to initialize all the elements of the variable Dataset to 0. Is this a correct way to initialize this variable ? Is it possible that this method initialize only the first element (val_a) to 0, but not all the elements if we initialize this many times ?

Yuan
  • 1
  • 2
  • What do you mean with "if we initialize this many times"? That suggest that the code in your question is part of a function (i.e. that `Dataset` is a local variable). If so, that's different than if `Dataset` is a global variable. Can you [edit] your question and clarify what your question is about? – wovano May 23 '22 at 12:57
  • Or [Why is {0} always a valid struct initializer?](https://stackoverflow.com/questions/63408168/why-is-0-always-a-valid-struct-initializer) – wovano May 23 '22 at 12:59

1 Answers1

0

The dupe does not answer the question completely.

In most cases (except one) {0} will initialize the struct as many times as the function is called.

If the struct is an static storage duration object defined in the local scope it will work only on the first call. Later the object will keep the value between the calls.

void foo(void)
{
     static dataset_t Dataset = {0};
     /* .... */
}

https://godbolt.org/z/6zE1YcE67

0___________
  • 60,014
  • 4
  • 34
  • 74