Samer.M
Samer.M

Reputation: 131

Initializing a static const array

I'm trying to initialize a static const array of the struct:

typedef struct{
UINT8 id_array[3];
} __attribute__((packed, aligned(1))) ST_ID;

I do the init as follows:

static const ST_ID msg_ids[3] = 
{
    /* Category A: Protocols */
    {0x8A,      0x01,   0x01}, \
    {0x8A,      0x02,   0x00}, \
    {0x8A,      0x03,   0x00}, \
};

i get warnings during compiling:

'note: (near initialization for ‘msg_ids' and 'warning: missing braces around initializer [-Wmissing-braces]'

and the values in run time are not correct!!

Upvotes: 0

Views: 5233

Answers (2)

Clifford
Clifford

Reputation: 93544

You strictly need a pair of braces to enclose the struct initialiser and a pair to enclose the array member initialiser; thus:

static const ST_ID msg_ids[3] = 
{
    { { 0x8A, 0x01, 0x01 } },
    { { 0x8A, 0x02, 0x00 } },
    { { 0x8A, 0x03, 0x00 } }
} ;

Your initialiser generates a warning rather then an error, but strict adherence makes maintenance simpler if for example you later add a member to the structure other than just the array.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320641

If you want to be pedantic with braces, then it should be

static const ST_ID msg_ids[3] = 
{
    { { 0x8A, 0x01, 0x01 } },
    { { 0x8A, 0x02, 0x00 } },
    { { 0x8A, 0x03, 0x00 } },
};

This is what GCC expects you to do.

However, I'd expect your original variant to produce correct values as well (albeit with that annoying GCC warning).

P.S. Why do you insist on using that \ at the end of each line inside the initializer?

Upvotes: 3

Related Questions