Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designated initializers and omitted elements

Tags:

c

Can anybody please explain the following line about the designated initializers:

The initializer list can omit elements that are declared anywhere in the aggregate, rather than only at the end.

like image 761
mawia Avatar asked Apr 18 '09 16:04

mawia


2 Answers

If you use a conventional initialiser list, the values for the elements are assigned in order, so if you have this struct:

typedef struct _foo {
  int a;
  int b;
} foo_t;

then this initialiser explicitly assigns a and not b:

foo_t value = { 7 };

without designated initialisers, the only elements which can be omitted are the ones declared at the end

using designated initialisers, you can omit elements that are declared anywhere:

foo_t value = { .b = 8 };

so the initialiser for value.a is omitted, despite being the first value in the struct.

like image 157
Pete Kirkham Avatar answered Sep 19 '22 23:09

Pete Kirkham


Try this link.

The idea is to be able to refer to members of a complex type like structure during initialization. E.g.

struct s {
   int a, b;
};

int main() {
  struct s = { .b = 42, .a = -42 };
  return 0;
}

The flexibility is gained from being order independent when specifying values. Remember this was added to the C99 standard and may not be supported by compilers which do not support C99 fully (or support an earlier version of the standard).

like image 41
dirkgently Avatar answered Sep 17 '22 23:09

dirkgently