Normally one would declare/allocate a struct on the stack with:
STRUCTTYPE varname;
What does this syntax mean in C (or is this C++ only, or perhaps specific to VC++)?
STRUCTTYPE varname = {0};
where STRUCTTYPE is the name of a stuct type, like RECT or something. This code compiles and it seems to just zero out all the bytes of the struct but I'd like to know for sure if anyone has a reference. Also, is there a name for this construct?
This is aggregate initialization and is both valid C and valid C++.
C++ additionally allows you to omit all initializers (e.g. the zero), but for both languages, objects without an initializer are value-initialized or zero-initialized:
// C++ code:
struct A {
int n;
std::string s;
double f;
};
A a = {}; // This is the same as = {0, std::string(), 0.0}; with the
// caveat that the default constructor is used instead of a temporary
// then copy construction.
// C does not have constructors, of course, and zero-initializes for
// any unspecified initializer. (Zero-initialization and value-
// initialization are identical in C++ for types with trivial ctors.)
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