Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C Nested Structs Initialization

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,
    };

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading