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

Initializing multiple of the same structs with the same values in C

I made a struct with a few members and want to create multiple structure variables with the same initial member values.

My struct is the following:

    struct tempSens {
      float temperature;
      volatile int updateTimer;
    };

I want to make 2 structure variables TS1 and TS2 that both initialize their members with .temperature = 40.0 and .updateTimer = 10

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

I thought I could do it as shown below, but this way TS1 is initialized with both members set to 0 and TS2 with the given values 40.0 and 10 respectively.


    tempSens TS1, TS2 = {40.0, 10};

I am looking for a more efficient way than doing:

    tempSens TS1 = {40.0, 10};
    tempSens TS2 = {40.0, 10};

Is there any way to achieve this without having to give the member values to each structure variable?

>Solution :

Inside a function, you can use tempSens TS1 = {40.0, 10}, TS2 = TS1;.

Inside or outside a function, you can use:

#define TSInitializer {40.0, 10}

tempSens TS1 = TSInitializer, TS2 = TSInitializer;

If you use GCC or Clang and use an array, you can use GCC’s range extension for designated initializers:

struct tempSens Array[100] = { [0 ... 99] = {40.0, 10} };
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