For years I have been initializing my struct stat
like this:
#include <sys/stat.h>
struct stat foo = {0};
Specifically, that {0}
set all the fields to zero, equivalent to memset (&foo, NULL, sizeof foo);
. Now with C++11, this has started yielding warnings:
foo.cpp:2:19: warning: missing field 'st_mode' initializer [-Wmissing-field-initializers]
struct stat s = {0};
^
This is because of the new initializer syntax of C++11, and the warning implies I am not initializing all members. What is the preferred way to instantiate and initialize a struct stat
in C++11?
Structure members can be initialized using curly braces '{}'.
2 ways to create and initialize a new structThe new keyword can be used to create a new struct. It returns a pointer to the newly created struct. You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field.
When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members: = { expression , ... }
You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.
Use
stat s{};
instead and it will do the job without any warnings. It is called value-initialization of the object. Although in your case struct stat foo = {0};
should perform aggregate initialization (assuming your struct stat
is an aggregate), and the remaining members should be value-initialized also, so technically the code is correct.
If your compiler is older and doesn't support struct s{}
syntax, you might still be able to use C99 syntax: struct stat s = { .st_dev = 0 };
Failing even that, or if you have to wipe one, memset( &s, 0, sizeof(struct stat) );
will always work.
Could this stem from a case of misunderstanding {0}
? You know that the 0
doesn't actually mean "set all fields to zero", right? It means "set the first field to zero" ... and all the other ones are left to the whim of the language (which, as it happens, will zero-initialise them anyway).
struct stat foo = {}
would more accurately describe your intention, and I suspect it would also take care of the warning.
Of course, nowadays, you can be absolutely clear by writing struct stat foo{};
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With