Concepts of Programming Languages

(Sean Pound) #1

408 Chapter 9 Subprograms


corresponding actual parameter (the number of actual parameters need not be
the same as the number of formal parameters) and it is a variable.
The parameter-passing method of Python and Ruby is called pass-by-
assignment. Because all data values are objects, every variable is a reference to
an object. In pass-by-assignment, the actual parameter value is assigned to the
formal parameter. Therefore, pass-by-assignment is in effect pass-by-reference,
because the value of all actual parameters are references. However, only in
certain cases does this result in pass-by-reference parameter-passing semantics.
For example, many objects are essentially immutable. In a pure object-oriented
language, the process of changing the value of a variable with an assignment
statement, as in

x = x + 1

does not change the object referenced by x. Rather, it takes the object refer-
enced by x, increments it by 1 , thereby creating a new object (with the value
x + 1), and then changes x to reference the new object. So, when a refer-
ence to a scalar object is passed to a subprogram, the object being referenced
cannot be changed in place. Because the reference is passed by value, even
though the formal parameter is changed in the subprogram, that change has
no effect on the actual parameter in the caller.
Now, suppose a reference to an array is passed as a parameter. If the cor-
responding formal parameter is assigned a new array object, there is no effect
on the caller. However, if the formal parameter is used to assign a value to an
element of the array, as in

list[3] = 47

the actual parameter is affected. So, changing the reference of the formal
parameter has no effect on the caller, but changing an element of the array
that is passed as a parameter does.

9.5.5 Type Checking Parameters


It is now widely accepted that software reliability demands that the types of
actual parameters be checked for consistency with the types of the correspond-
ing formal parameters. Without such type checking, small typographical errors
can lead to program errors that may be difficult to diagnose because they are
not detected by the compiler or the run-time system. For example, in the
function call

result = sub1(1)

the actual parameter is an integer constant. If the formal parameter of sub1 is
a floating-point type, no error will be detected without parameter type check-
ing. Although an integer 1 and a floating-point 1 have the same value, the
Free download pdf