Paul Beckingham
Paul Beckingham

Reputation: 14895

How do I properly initialize 'struct stat' using C++11?

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?

Upvotes: 8

Views: 5280

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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{};.

Upvotes: 1

Davislor
Davislor

Reputation: 15144

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.

Upvotes: 1

vsoftco
vsoftco

Reputation: 56547

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.

Upvotes: 10

Related Questions