You are here

Defning an Array in C++

10 February, 2015 - 16:31


int ages[5] = {49,48,26,l9,l6}; 

This is the defining of storage space. The square brackets (left [ and right ]) are used here to create the array with five integer members and the identifier name of ages. The assignment with braces (that is a block) establishes the initial values assigned to the members of the array. Note the use of the sequence or comma operator. We could have done it this way:

int ages[] = {49,48,26,l9,l6}; 

By leaving out the five and having initial values assigned, the compiler will know to create the array with five storage spaces because there are five values listed. This method is preferred because we can simply add members to or remove members from the array by changing the items inside of the braces. We could have also done this:

int ages[5];

This would have declared the storage space of five integers with the identifier name of ages but their initial values would have been unknown values (actually there would be values there but we don't know what they would be and thus think of the values as garbage). We could assign values later in our program by doing this:

ages[0] = 49; ages[l] = 48; ages[2] = 26; ages[3] = l9; ages[4] = l6; 

Note: The members of the array go from 0 to 4; NOT 1 to 5. This is explained in more detail in another Connexions module that covers accessing array members and is listed in the supplemental links provided. See: Array Index Operator.