Next: Accessing Array Elements Up: Arrays in C++ Previous: Arrays in C++

Declaration of Arrays

An array declaration is very similar to a variable declaration. First a type is given for the elements of the array, then an identifier for the array and, within square brackets, the number of elements in the array. The number of elements must be an integer.

For example data on the average temperature over the year in Britain for each of the last 100 years could be stored in an array declared as follows:

float annual_temp[100];

This declaration will cause the compiler to allocate space for 100 consecutive float variables in memory. The number of elements in an array must be fixed at compile time. It is best to make the array size a constant and then, if required, the program can be changed to handle a different size of array by changing the value of the constant,

const int NE = 100;
float annual_temp[NE];
then if more records come to light it is easy to amend the program to cope with more values by changing the value of NE. This works because the compiler knows the value of the constant NE at compile time and can allocate an appropriate amount of space for the array. It would not work if an ordinary variable was used for the size in the array declaration since at compile time the compiler would not know a value for it.



Next: Accessing Array Elements Up: Arrays in C++ Previous: Arrays in C++