0

I am trying to create an array of const structs, but i Keep getting

error initializer element is not a compile time constant

I am using keil IDE. this is strange because my struct is a const, here is an example:

typedef const struct{
     CRGB color;  // CRGB is another struct
     void (*myfunc)(int);
}myProfile;


myProfile profile1 = { ....... }; // initialized struct

myProfile profiles[1] = { profile1 }; // error occurs here

even if I use const myProfile profile1 = { ..... }; to initialize the struct, i still get the same errors.

I can find my way around it but I really want to understand what is going on. Thanks.

ched
  • 83
  • 3
  • 10
  • The initializer must be a *constant expression* which is a stronger condition than just a variable with `const` qualification. In fact a variable is never a constant expression. – M.M Oct 24 '18 at 22:23
  • can you give me an example of what you mean for clarity @M.M I could do something like this `#define profile1 (myProfile){.....} ` what other options do I have? – ched Oct 24 '18 at 22:54
  • Be wary of using `const` in a typedef (you're braver than I am using it there). You could use `myProfile *profiles[1] = &profile1;`, initializing the pointer in the array with the constant address the other profile. This might get you a result you can live with; you might add `const` qualifiers to the pointers. – Jonathan Leffler Oct 25 '18 at 00:41
  • Thank you Jonathan, you are right. But in this case, the profiles are meant to be constant anyway. – ched Oct 26 '18 at 07:20

1 Answers1

0

The error occurs because you try to initialize the array with a variable, which is not a constant (= a fixed value known at compile time), as M.M mentioned in the comments.

If you want to create a default value for your structure, you could do as shown here.

Building on that answer, you would initialize a table with:

MyStruct instances[2] = {MyStruct_default, MyStruct_default};

Which is a shortcut for:

MyStruct instances[2] = { {.id = 3}, {.id = 3} };

Note that for a structure composed of multiple members, you can leave some blank and they should be set to 0 most of the time.

DRz
  • 1,078
  • 1
  • 11
  • 29