0

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!!

5
  • 1
    and the values in run time are not correct!!...minimal reproducible example please. Commented Jun 26, 2016 at 12:12
  • What is UINT8? Don't use homebrew fixed-width types. Use the standard types instead. Commented Jun 26, 2016 at 16:16
  • You don't need the `\` newline escape at the end of every line - this is not a macro. Commented Jun 26, 2016 at 16:56
  • You also have a superfluous comma after the last initialiser. Commented Jun 26, 2016 at 16:58
  • Is that first warning complete? It does not make much sense on its own. GCC can split diagnostics across multiple lines that some IDE filter out - post the text from the raw compiler output rather than any filtered message list. Commented Jun 26, 2016 at 17:08

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.