I want to initialise all members of the array to zero, or nullptr
struct Window{ int a;};
int main()
{
Window* list[4] = { 0, 0, 0, 0 };
Window* list2[4] = {0};
Window* list3[4] = {};
Window* list4[4]{ 0, 0, 0, 0 };
Window* list5[4]{0};
Window* list6[4]{};
}
I understand that when initialising at least one member to any value all the others are zero initialised, so if I do:
int list[4] = { 6 };
The first member becomes 6
and all the rest are zero-initialised. I'm confused however with:
int list[4]{0};
and
int list[4]{};
I assume that the empty squiggly brackets right after the declaration without an equals sign are what's called zero initialisation, as opposed to default initialisation, but so too is int list[4]{0}
, isn't it? Does this involve an std::initializer_list
behind the scenes or not? I thought these were only used for non-POD types, so std::initializer_list
is not being used here?
Is there a difference between these ways of initialising a C array in C++?
No. They're semantically equivalent.
zero initialisation, as opposed to default initialisation, but so too is int list[4]{0}, isn't it?
The first element is copy-initialized with zero. The rest of the elements are value initialized, which for int
is indeed zero initialization. There is no effectual difference in value, zero and copy initialization with zero specifically in the case of int
specifically. The distinction is syntactical in that case.
Does this involve an std::initializer_list behind the scenes or not?
std::initializer_list
is not involved.
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