0

What is the meaning of standalone square brackets inside of a C array of a custom type?

typedef enum {
    BAR_1 = 0,
    BAR_2,
    BAR_3,
} bar_types;

typedef struct {
    int is_interesting;
    int age;
} foo_s;

static foo_s bars[] = {
    [BAR_1] = {1, 2},  /* What is being done here? */
    [BAR_2] = {1, 41},
    [BAR_3] = {0, 33},
};

In the above code, what is the meaning of [BAR_1] = {1, 2}? When is it possible to use standalone square brackets?

I've noticed that if I add duplicate value in brackets, clang gives an warning about subobject initialisation.

static foo_s bars[] = {
    [BAR_1] = {1, 2},
    [BAR_2] = {1, 41},
    [BAR_3] = {0, 33},
    [BAR_3] = {0, 33},
};

-----

$clang example.c
example.c:17:19: warning: subobject initialization 
  overrides initialization of other fields within its
  enclosing subobject [-Winitializer-overrides]
    [BAR_3] = {0, 33},
              ^~~~~~~

What is a C subobject?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Those just designate specific array elements to be initialised. The enum values act like the corresponding `int` values, so `[BAR_1] = {1, 2}` becomes `[0] = {1, 2}`, meaning the first struct in the array (index 0) gets initialised with `is_interesting` as 1 and `age` as 2. – Dmitri Feb 20 '17 at 03:25
  • For what a subobject is, see http://stackoverflow.com/questions/18451683/c-disambiguation-subobject-and-subclass-object – racraman Feb 20 '17 at 03:29
  • "subobject" is any object contained within another object. – M.M Feb 20 '17 at 03:36
  • 1
    The notation is one species of 'designated initializer'. – Jonathan Leffler Feb 20 '17 at 04:03
  • 1
    @racraman That is a C++ question. This is about C. – 2501 Feb 20 '17 at 08:47

1 Answers1

2

this is struct initialization, the "subobject" is the instance of the struct that is getting initialized.

Your warning comes from trying to initialize the same array position twice.

also see How to initialize a struct in accordance with C programming language standards

Community
  • 1
  • 1
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156