short months[12];
An array is a derived type because it is based on some other type.
One can access the array elements individually. The way to do this is to use a subscript, or index, to number the elements. C++ array numbering starts with 0, using a barcket notation with the index to specify an array element.
For example, months[0]
is the first element of the months
array, and months[11]
is the last element.
Note that the index of the last element is one less than the size of the array.
C++ lets you initialize array elements within the declaration statement.
int eggCosts[3] = { 4, 5, 3 };
Simply provide a comma-seperated list of values ( the initialization list) enclosed in braces. The spaces in the list are optional. If you don't initialize an array that's defined inside a function, the element values remain undefined. The element takes on whatever value previously resided at that location in memory.
The sizeof
operator when used with an array name, will return the number of bytes in the whole array. But if you use the sizeof
with an array element, you get the size, in bytes, of the element.
int cards[4] = {3, 6, 8, 10}; // okay =)
int hand[4]; // okay =)
hand[4] = {5, 6, 7, 9}; // not allowed =(
hand = cards; // not allowed =(
int yams[3]
yams[0] = 7;
yams[1] = 7;
yams[2] = 7;
float hotelTips[5] = {5.0, 2.5};
float totals[500] = {0};
[]
) when you initialize an array, the C++ compiler counts the elements for you.