Initializing Built-In Arrays

You can initialize the elements of a built-in array using an initializer list. For example,

int n[ 5 ] = { 50, 20, 30, 10, 40 };

Image

creates a built-in array of five ints and initializes them to the values in the initializer list. If you provide fewer initializers than the number of elements, the remaining elements are value initialized—fundamental numeric types are set to 0, bools are set to false, pointers are set to nullptr and class objects are initialized by their default constructors. If you provide too many initializers a compilation error occurs. The new C++11 list-initialization syntax that we introduced in Chapter 4 is based on the built-in array initializer-list syntax.

If a built-in array’s size is omitted from a declaration with an initializer list, the compiler sizes the built-in array to the number of elements in the initializer list. For example,

int n[] = { 50, 20, 30, 10, 40 };

creates a five-element array.


Image Error-Prevention Tip 8.3

Always specify a built-in array’s size, even when providing an initializer list. This enables the compiler to ensure that you do not provide too many initializers.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.2