Next: Example Program: Printing Outliers
Up: Arrays in C++
Previous: Accessing Array Elements
The initializations of simple variables in their declaration has already been covered. An array can be initialised in a similar manner. In this case the initial values are given as a list enclosed in curly brackets. For example initialising an array to hold the first few prime numbers could be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11, 13};Note that the array has not been given a size, the compiler will make it large enough to hold the number of elements in the list. In this case
primes
would be allocated space for seven elements. If
the array is given a size then this size must be greater than or equal
to the number of elements in the initialisation list. For example:int primes[10] = {1, 2, 3, 5, 7};would reserve space for a ten element array but would only initialise the first five elements.