|
|
| |
|
|
|
|
C, C++, and Parameter Passage of Arrays |
|
|
|
| |
|
|
|
|
Some programming languages allow arrays to be passed either by value or by reference. Remember that with passage by value, a copy of the actual parameter is sent to the function. When an array is passed by value, the entire array is copied. Not only is extra space required in the function to hold the copy, but the copying itself takes time. Passage by reference requires only that the address of the actual parameter be passed to the function, so when an array is passed by reference, just the address of the first array component is passed. Thus, passing large arrays by reference saves both memory and time. |
|
|
|
| |
|
|
|
|
The C programming language-the direct predecessor of C++-was originally designed to be a system programming language. System programs, such as compilers, assemblers, linkers, and operating systems, must be both fast and economical with memory space. In the design of the C language, passing arrays by value was judged to be an unnecessary language feature. Serious system programmers never used pass-by-value when working with arrays. Therefore, both C and C++pass arrays only by reference. |
|
|
|
| |
|
|
|
|
Of course, using a reference parameter can lead to inadvertent errors if the values are changed within the function. In early versions of the C language, there was no way to protect the caller's array from being modified by the function. |
|
|
|
| |
|
|
|
|
C++(and recent versions of C) added the ability to declare a formal array parameter as const. By declaring the array as const, a compile-time error occurs if the function attempts to modify the array. As a result, C++ supports the efficiency of passing arrays by reference yet also provides the protection (through const) of passage by value. |
|
|
|
| |
|
|
|
|
Whenever your design of a function's interface identifies an array parameter as incoming-only (to be inspected but not modified by the function), declare the array as const to obtain the same protection as passage by value. |
|
|
|
|
|
|
|
|
|
The size of an array-the declared number of array components-is established at compile time. We have to declare it to be as big as it would ever need to be. Because the exact number of values to be put into the array is often dependent on the data itself, however, we may not fill all of the array components with values. The problem is that, to avoid processing empty ones, we must keep track of how many components are actually filled. |
|
|
|
|
|
|
|
|
As values are put into the array, we keep a count of how many components are filled. We then use this count to process only components that have values stored in them. Any remaining places are not processed. For example, if there are 250 students in a class, a program to analyze test grades |
|
|
|
|
|