0

I came across this code construct in Linux and would like to understand it

struct mystruct {
  int x;
  int b[40];
};


/*later */

static struct mystruct e = { .x = 5,
                             .b = {-1},   
                           };

What does .b = {-1} do ? Does it initialize only the first or all elements of array b ? How does it work ?

1

2 Answers 2

3
static struct mystruct e = {
    .x = 5,
    .b = {-1},   
             };

here it initializes b[0] to -1. other elements are initialized to 0.

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

Comments

1

It means initialize the member b of the struct with an array that starts with -1 and followed by 0

  • The .b = is a GCC extensions. (as commented, from C99 this is part of the standard as well)
  • The {-1} is standard array initialization.

2 Comments

Designated initialisers were introduced in C99 (but IIRC gcc is the only platform that implements c99) So, calling it a gcc extension would be unfair.
Considering the positioning of the code (inside the braces of a struct initialization), I don't think it's totally correct to call the = part of the standard notation. Before C99, you would have written this as e = { 5, { -1 } };, without the equals.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.