I have a struct with a few double values:
struct A {
double a;
double b;
}
if I create a new struct, e.g. A a
, are all the members (e.g. a.a
) initialized to zeroes automatically in C++?
I have a struct with a few double values:
struct A {
double a;
double b;
}
if I create a new struct, e.g. A a
, are all the members (e.g. a.a
) initialized to zeroes automatically in C++?
Not by default (unless it's a variable of static storage - that is, a
static
or global variable).There are a few ways to initialize a struct of this kind to "zeros":
or if you have a C++11 compatible compiler:
or add a constructor to the
struct
definition:No. In the general case, they have unspecified values.
If you don't like this behaviour, you can provide a constructor:
and (ordering reversed for readability):
They are default initialized. For builtin types like
int
ordouble
, their value depends on where the struct is declared (as a rule of thumb (but just as that): Assume they are always garbage unless initialized).In global scope or/and with
static
storage, they are all zeroes (incl. when the struct is a member of a struct which is at global scope).At function-local scope, they are full of garbage.
Example:
This on the first run gives me
On the second run, without recompilation, this gives me:
A POD-struct can be initialized all zeroes using e.g.
memset
or just ...