I just came across this array declaration:
const int nNums= 4;
int* nums[nNums] = {0, 0, 0}, d[nNums];
I understand that a pointer to nums is being created, but what is the business on the right? d[] gets initialized, but I am not quite sure what the {0,0,0} does.
int* nums[nNums] = {0, 0, 0} defined a array of 4 integer pointers each initialized to NULL. However, note that d is an array of integers and not integer pointers and these values are not initialized.
That code is equivalent to:
const int nNums= 4;
int* nums[nNums] = {0, 0, 0};
int d[nNums];
So, nums is an array of int*s of length 4, with all four elements initialized to null; d is an array of ints of length 4, with all four elements uninitialized (to reemphasize, d does not get initialized in any way).
The syntax = {0, 0, 0} in this context is known as "aggregate initialization", and is described in §8.5.1 of the C++03 standard; the relevant portion for this code (§8.5.1/2) states:
When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.
So, the first three elements of nums are explicitly initialized to 0, and the fourth element is implicitly "value-initialized", as stated in §8.5.1/7:
If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized.
Value-initialization is described in §8.5/5:
To value-initialize an object of type
Tmeans:
- if
Tis a class type with a user-declared constructor, then the default constructor forTis called (and the initialization is ill-formed ifThas no accessible default constructor);- if
Tis a non-union class type without a user-declared constructor, then every non-static data member and base-class component ofTis value-initialized;- if
Tis an array type, then each element is value-initialized;- otherwise, the object is zero-initialized
To zero-initialize an object of type
Tmeans:
- if
Tis a scalar type, the object is set to the value of0(zero) converted toT;- if
Tis a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;- if
Tis a union type, the object’s first named data member) is zero-initialized;- if
Tis an array type, each element is zero-initialized;- if
Tis a reference type, no initialization is performed.
This results in the fourth element of nums also being initialized to null.
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