Home > Blockchain >  C structure definition with default initialization?
C structure definition with default initialization?

Time:11-28

Sorry for asking this, as I'm sure it's been answered, but I've tried searching different terms for the last 30 minutes with no luck finding a definition similar to this.

struct {
    volatile uint8_t tail;
    uint8_t buf[128];
} uart = {0,0};

In the definition of the structure above, I do not understand what the purpose is of "= {0,0}" at the end.

What is this called? What is its purpose?

If I were to venture a guess, it's some sort of default value initializer, guessing it sets tail to 0 and the array is 0 filled when a new variable of "uart" type is defined. This is probably a duplicate of some question and I missed a keyword needed for it.

Edit: Just had another idea... Is this some sort of in-line struct definition and initializing a variable called uart? IE, it doesn't define a struct named uart, but defines a variable called uart, in-lines the struct definition, then sets the values. Very unusual, if so. I've never thought of in-lining a struct definition.

CodePudding user response:

There is no default initialization in C as C objects do not have constructors.

The only exception: not initialized static storage duration objects which are zeroed.

uart = {0,0};

It implicity initializes uart variable with two zeroes. It is better to write it {0, {0,}} as the second member is an erray.

  • Related