0

I am porting some C code to C++ and I am trying to initialize a struct with some values. I want the struct to be stored in flash (const) and not in RAM, and its values are typedef'd elements.

Originally, I had it like this:

typedef struct
{
    typeA_t elementA;
    typeB_t elementB;
    uint8_t elementC;
} structTypeA_t;

And to instantiate them in flash, I simply did the following:

const structTypeA_t sA = {
    .elementA = ONE,
    .elementB = TWO,
    .elementC = 3
};

I know that this type of initializing is not allowed in C++. How can I achieve it in C++?

  • 2
    It's allowed in C++20 (with some restrictions). Do you need a solution for older standard versions? – Dan M. Apr 22 '19 at 15:26

2 Answers2

3

Designated initializers are not in C++ (yet, but look for C++20). So you do it almost the same way, but without names - position of the argument defines the field it initializes:

const structTypeA_t sA = {ONE,
                          TWO,
                          3
};
SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

If you always need to initialize with the same values, then you can just define the struct like this:

struct structTypeA_t
{
    typeA_t elementA = ONE;
    typeB_t elementB = TWO;
    uint8_t elementC = 3;
};

You can now instantiate it without an initializer:

const structTypeA_t sA;
Nikos C.
  • 50,738
  • 9
  • 71
  • 96