169
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?

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
Benjamin
  • 10,085
  • 19
  • 80
  • 130

4 Answers4

189

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.

Dmitri
  • 9,175
  • 2
  • 27
  • 34
  • 2
    Does the dot initialization work in C++ too? (I need to test it) – Gabriel Staples Apr 12 '19 at 17:22
  • 4
    It appears that it does, but only for C++20, just looking at the documentation. Here's the cppreference.com documentation for C (works since C99): https://en.cppreference.com/w/c/language/struct_initialization, and for C++ (only works for C++20): https://en.cppreference.com/w/cpp/language/aggregate_initialization. – Gabriel Staples Apr 12 '19 at 17:25
  • Note that I just tried this "dot initialization" type form for C++ using gcc, and it appears that all versions of gcc C++ support it, so I bet it's supported by gcc as a gcc extension, meaning that prior to C++20 I suspect it is not portable necessarily to non-gcc/g++ compilers. That being said, though, I'm using gcc/g++ compilers so if it's supported by gcc for C++, I might as well use it. – Gabriel Staples Nov 09 '19 at 07:10
  • There is a potential gotcha in dot initialization (at least with some compilers). `struct demo_s demo = { .first = 1, .first = 9 };` On one of my GCC this will compile without warning and first will be 9. – Renate Feb 08 '20 at 02:16
26

These are C99's designated initializers.

Dan Aloni
  • 3,968
  • 22
  • 30
18

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.

COD3BOY
  • 11,964
  • 1
  • 38
  • 56
-3

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.

ind79ra
  • 149
  • 2
  • 13