I'm aware of int a[10]={0}
and int a[10]={}
but can you now also do int a[10]{}
in c++ to initialize an automatic variable?
All three are valid, but different initialization methods.
Since C++11 it goes something like this:
={0}
is copy-list-initialization with a single element braced-init-list, which for a an array (because arrays are aggregate types) results in aggregate initialization from a single element, which in turn means that the first element of the array is initialized explicitly with 0
and the rest is implicitly value-initialized, meaning for int
, they are zero-initialized, i.e. also initialized to 0
.
(There are a few exceptions where aggregate initialization is not performed for a single element braced-init-list even for an aggregate. Specifically if the single element is the same type or a type derived from the target type that is being initialized and if the single element is a string literal and the target a character array. In these situations the variable is initialized from the element of the braced-init-list instead.)
={}
is copy-list-initialization with an empty braced-init-list, which does in the same way end up as _aggregate initialization, only that now no element of the array is explicitly initialized. Instead all of them are implicitly value-initialized and therefore zero-initialized.
{}
is direct-list-initialization with an empty braced-init-list. For aggregate types there is no difference between direct-list-initialization and copy-list-initialization. They both end up as aggregate initialization. (In the first of the two exceptional cases I mentioned above there is a difference between the two, because the target would be direct-initialized or copy-initialized from the single element respectively.)
So in the end all three are valid and all of them initialize all of the int
elements to 0
. More generally for arrays of scalar types all elements will be zero-initialized in all three variants.
However, for other types all three may have different behavior. Iterating all the relevant rules is unfortunately completely impossible in the scope of an answer here. In particular it is also possible to initialize non-aggregate types with list-initialization and it behaved differently from non-list-initialization in certain ways.
Before C++11 there was no general list-initialization, but only aggregate initialization, which was permitted only in the form using =
.
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