C (or C ++?) Syntax: STRUCTTYPE varname = {0};

You can usually declare / allocate a structure on the stack with:

STRUCTTYPE varname; 

What does this syntax mean in C (or is it just C ++, or perhaps specific to VC ++)?

 STRUCTTYPE varname = {0}; 

where STRUCTTYPE is a name of type stuct, such as RECT or something else. This code compiles and it seems to just zero out all the bytes of the structure, but I would like to know for sure if anyone has a link. Also, is there a name for this design?

+4
source share
2 answers

This is aggregated initialization and is valid C and valid C ++.

C ++ additionally allows you to omit all initializers (for example, zero), but for both languages ​​objects without an initializer are initialized with initialization or initialized with zero:

 // 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.) 
+8
source

In C, the initializer {0} valid for initializing any variable of any type for all null values. In C99, this also allows you to assign a "zero" to any modifiable lvalue of any type using a composite literal syntax:

 type foo; /* ... */ foo = (type){0}; 

Unfortunately, some compilers will give you warnings about the presence of an “incorrect number” of brackets around the initializer if the type is a base type (for example, int x = {0}; ) or a nested structure / array type (for example, struct { int i[2]; } x = {0}; ). I would call such warnings harmful and disable them.

+3
source

Source: https://habr.com/ru/post/1338337/


All Articles