What does dot (.) mean in a struct initializer?

50.4k views Asked by At
static struct fuse_oprations hello_oper = {
  .getattr = hello_getattr,
  .readdir = hello_readdir,
  .open    = hello_open,
  .read    = hello_read,
};

I don't understand this C syntax well. I can't even search because I don't know the syntax's name. What's that?

4

There are 4 answers

4
Dmitri On BEST ANSWER

This is a C99 feature that allows you to set specific fields of the struct by name in an initializer. Before this, the initializer needed to contain just the values, for all fields, in order -- which still works, of course.

So for the following struct:

struct demo_s {
  int     first;
  int     second;
  int     third;
};

...you can use

struct demo_s demo = { 1, 2, 3 };

...or:

struct demo_s demo = { .first = 1, .second = 2, .third = 3 };

...or even:

struct demo_s demo = { .first = 1, .third = 3, .second = 2 };

...though the last two are for C99 only.

0
Dan Aloni On

These are C99's designated initializers.

0
COD3BOY On

Its known as designated initialisation (see Designated Initializers). An "initializer-list", Each '.' is a "designator" which in this case names a particular member of the 'fuse_oprations' struct to initialize for the object designated by the 'hello_oper' identifier.

0
ind79ra On

The whole syntax is known as designated initializer as already mentioned by COD3BOY and it is used in general when you need to initialize your structure at the time of declaration to some specific or default values.