< previous page page_608 next page >

Page 608
Passing Arrays as Parameters
In Chapter 8, we said that if a variable is passed to a function and it is not to be changed by the function, then the variable should be passed by value instead of by reference. We specifically excluded stream variables (such as those representing data files) from this rule and said that there would be one more exception. Arrays are this exception.
By default, C++ simple variables are always passed by value. To pass a simple variable by reference, you must append an ampersand (&) to the data type name in the formal parameter list:
int SomeFunc( float param1,    // Passed by value
              char& param2 )   // Passed by reference
{
  .
  .
  .
}
It is impossible to pass a C++ array by value; arrays are always passed by reference. Therefore, you never use ''&" when declaring an array as a formal parameter. When an array is passed as a parameter, its base address-the memory address of the first element of the array-is sent to the function. The function then knows where the caller's actual array is located and can access any element of the array.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Base Address The memory address of the first element of an array.
Here is a C++ function that will zero out a one-dimensional float array of any size:
void ZeroOut( /* out */ float arr[],
              /* in */ int   numElements )
{
    int i;

    for (i = 0; i < numElements; i++)

            // Invariant (prior to test):
            //     arr[0..i-l] == 0.0
            //  && 0 <= i <= numElements

        arr[i] = 0.0;
}

 
< previous page page_608 next page >