If I have a common linux struct like:
struct sockaddr_in
{
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
unsigned char __pad[__SOCK_SIZE__ - sizeof(short int)
- sizeof(unsigned short int) - sizeof(struct in_addr)];
};
#define sin_zero __pad
and I perform aggregate initialization:
struct sockaddr_in my_addr = { 0 };
how come that this initializes every member to 0?
I mean: documentation says:
If the number of initializer clauses is less than the number of members or initializer clauses is completely empty, the remaining members are initialized by their brace-or-equal initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, which performs value-initialization.
to make it easy: why does this code print 0?
struct sockaddr_in my_addr = {2, 2}; // initialize sin_family and sin_port to 2, everything else value-initialized
my_addr = {0};
std::cout << my_addr.sin_port; // Why is this 0?
{0}
creates a temporarysockaddr_in
with that initializer and then=
copies the entire temporary over. – T.C.static
(i. e. with 0). – The Paramagnetic Croissantmy_addr
are copy-initialized straight from the list elements – Jonathan Wakelystruct sockaddr_in my_addr = { 0 };
snippet earlier in the question. I should have noticed that you said{0}
not{ 0 }
:-) – Jonathan Wakely