Concepts of Programming Languages

(Sean Pound) #1
6.5 Array Types 265

the compiler sets the length of the array. This is meant to be a convenience
but is not without cost. It effectively removes the possibility that the system
could detect some kinds of programmer errors, such as mistakenly leaving a
value out of the list.
As discussed in Section 6.3.2, character strings in C and C++ are imple-
mented as arrays of char. These arrays can be initialized to string constants,
as in


char name [] = "freddie";


The array name will have eight elements, because all strings are terminated
with a null character (zero), which is implicitly supplied by the system for
string constants.
Arrays of strings in C and C++ can also be initialized with string literals. In
this case, the array is one of pointers to characters. For example,


char *names [] = {"Bob", "Jake", "Darcie"};


This example illustrates the nature of character literals in C and C++. In the
previous example of a string literal being used to initialize the char array
name, the literal is taken to be a char array. But in the latter example (names),
the literals are taken to be pointers to characters, so the array is an array of
pointers to characters. For example, names[0] is a pointer to the letter 'B'
in the literal character array that contains the characters 'B', 'o', 'b', and
the null character.
In Java, similar syntax is used to define and initialize an array of references
to String objects. For example,


String[] names = ["Bob", "Jake", "Darcie"];


Ada provides two mechanisms for initializing arrays in the declaration
statement: by listing them in the order in which they are to be stored, or by
directly assigning them to an index position using the => operator, which in
Ada is called an arrow. For example, consider the following:


List : array (1..5) of Integer := (1, 3, 5, 7, 9);
Bunch : array (1..5) of Integer := (1 => 17, 3 => 34,
others => 0);


In the first statement, all the elements of the array List have initializing values,
which are assigned to the array element locations in the order in which they
appear. In the second, the first and third array elements are initialized using
direct assignment, and the others clause is used to initialize the remaining
elements. As with Fortran, these parenthesized lists of values are called aggre-
gate values.

Free download pdf