What does dot (.) mean in a struct initializer?
40,177
Solution 1
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.
Solution 2
These are C99's designated initializers.
Solution 3
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.
Related videos on Youtube
Comments
-
Benjamin about 4 years
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?
-
Mysticial over 12 yearsIt looks like a struct initializer.
-
Some programmer dude over 12 yearsStandardized in C99, so wont work if you have a (really) old compiler.
-
Mysticial over 12 yearsFinally found the link for this: stackoverflow.com/questions/330793/…
-
Jonathan Leffler over 12 yearsUnfortunately, even the current versions of MSVC are '(really) old compilers' by this standard.
-
Keegan Jay about 6 yearsAbsolutely bizarre, I searched this question while also going through a fuse tutorial, and writing that exact same initializer.
-
-
Gabriel Staples about 5 yearsDoes the dot initialization work in C++ too? (I need to test it)
-
Gabriel Staples about 5 yearsIt 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): en.cppreference.com/w/c/language/struct_initialization, and for C++ (only works for C++20): en.cppreference.com/w/cpp/language/aggregate_initialization.
-
Gabriel Staples over 4 yearsNote 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.
-
Renate over 4 yearsThere 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.