Reputation: 1301
I have a struct that looks something like this:
typedef struct
{
uint32_t a;
uint32_t b;
uint32_t c[5];
uint32_t d;
} MY_STRUCT_T;
I want to initialize c
, by name, to a non-zero value. I want everything else to be 0.
If c
were not an array, I could do:
static MY_STRUCT_T my_struct = {.b = 1};
And I know I can do this:
static MY_STRUCT_T my_struct = {.c[0]=5,
.c[1]=5,
.c[2]=5,
.c[3]=5,
.c[4]=5};
but I was wondering if there was a more elegant syntax of which I am unaware: Something like:
static MY_STRUCT_T my_struct = {.c[] = {5,5,5,5,5}};
I have read the following, but they don't answer this question:
Initializing a struct to 0
Initialize/reset struct to zero/null
A better way to initialize a static array member of a class in C++ ( const would be preferred though )
How to initialize all members of an array to the same value?
Upvotes: 4
Views: 238
Reputation: 153498
OP has 3 goals: 1) field array size is fixed width, 2) initialization like {7,7,7,7,7}
is fixed width, 3) c
to a non-zero value. As #1 and #2 have their sizes independent coded, 2 of the 3 goals can be met, but not all 3 - that is tricky.
What is to prevent/warn about MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}};
not meeting goals should uint32_t c[5];
later become uint32_t c[6];
? Nothing really.
Lacking a maintainable coding paradigm, consider this - copy one by one
Upvotes: 0
Reputation: 1301
So I wrote this question and then experimented for a while and found that the following would work:
static MY_STRUCT_T my_struct = {.c={5,5,5,5,5}};
Upvotes: 3