Cpp - Array Array Initializing

Introduction

You can initialize a array when declaring the array.

int my_array[10] = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }; 

The code above declares my_array to be an array of 10 integers.

It assigns my_array[0] the value 0, my_array[1] the value 10, and so forth up to my_array[9] equaling 90.

If you omit the size of the array, the C++ compiler would set the size for you.

Consider this statement:

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

An integer array with five elements is created with my_array[0] equal to 10, my_array[1] equal to 20, and so on.

The sizeof operator can count the number of elements in an array:

const int size = sizeof(my_array) / sizeof(my_array[0]); 

This example obtains the size of the my_array array by dividing the size of the entire array by the size of an individual element in the array.

The result is the number of members in the array.

You cannot initialize more elements than you've declared for the array. This statement generates a compiler error:

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

It is permitted to initialize an array with fewer values than it holds, as in this statement:

int long[5] = { 10, 20 };