Programming in C

(Barry) #1
Pointers and Arrays 263

return sum;
}

int main (void)
{
int arraySum (int array[], const int n);
int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 };

printf ("The sum is %i\n", arraySum (values, 10));

return 0;
}

Program 11.11 Output
The sum is 21

Inside the arraySumfunction, the constant integer pointer arrayEndis defined and set
pointing immediately after the last element of array.A forloop is then set up to
sequence through the elements of array.The value of ptris set to point to the begin-
ning of arraywhen the loop is entered. Each time through the loop, the element of
arraypointed to by ptris added into sum.The value of ptris then incremented by the
forloop to set it pointing to the next element in array.When ptrpoints past the end
of array,the forloop is exited, and the value of sumis returned to the calling routine.

A Slight Digression About Program Optimization
It is pointed out that the local variable arrayEndwas not actually needed by the func-
tion because you could have explicitly compared the value of ptrto the end of the array
inside the forloop:
for ( ...; pointer <= array + n; ... )
The sole motivation for using arrayEndwas one of optimization. Each time through the
forloop, the looping conditions are evaluated. Because the expression array + nis
never changed from within the loop, its value is constant throughout the execution of
the forloop. By evaluating it once beforethe loop is entered, you save the time that
would otherwise be spent reevaluating this expression each time through the loop.
Although there is virtually no savings in time for a 10-element array, especially if the
arraySumfunction is called only once by the program, there could be a more substantial
savings if this function were heavily used by a program for summing large-sized arrays,
for example.
The other issue to be discussed about program optimization concerns the very use of
pointers themselves in a program. In the arraySumfunction discussed earlier, the

Program 11.11 Continued

TEAM FLY

Free download pdf