Home > database >  C Nested Structs Initialization
C Nested Structs Initialization

Time:09-16

I'm an avid embedded c programmer. I recently started working with the ESP IDF framework to program the ESP32. Even though I think that the following code is initializing a struct within a struct (not sure); but for some reason, I cannot grasp how and why there is just a ".mode" rather than the struct's name within gpio_config_t ".mode". This is just an example but there are several instances of similar types of initialization.

for example:

typedef struct example_struct{
int mode;
int pull_up_en;
.
.
}example_struct;

typedef struct gpio_config_t
{
 example_struct test;
} gpio_config_t;

Shouldn't the initialization be done the following way?

gpio_config_t io_test_config = 
{
test.mode = 3; 
test.pull_up_en = 1; 
etc
};

Can someone please clarify this?

The actual type of initialization I'm referring to:

gpio_config_t io_conf = {
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = 1,
    };

CodePudding user response:

The technical term for the notation you're using is designated initializers. The designators always start with either a . or a [, and there are no semicolons in the initializers (until after the } at the end of the initializer). There are many ways that you could initialize that structure, including:

gpio_config_t io_test_config1 = 
{
    .test.mode = 3, .test.pull_up_en = 1
};

gpio_config_t io_test_config2 = 
{
    .test = { .mode = 3, .pull_up_en = 1 }
};

gpio_config_t io_test_config3 = 
{
    { 3, 1 }
};

gpio_config_t io_test_config4 = 
{
    3, 1 
};

The last one doesn't compile cleanly with GCC when you specify -Wmissing-braces (usually activated by -Wall).

  • Related