Concepts of Programming Languages

(Sean Pound) #1
9.6 Parameters That Are Subprograms 417

list[i] = 5;
fun(i, list[i]);
}

In fun, if pass-by-reference is used, i and a are aliases. If pass-by-value-result
is used, i and a are not aliases. The actions of fun, assuming pass-by-value-
result, are as follows:

addr_i = &i — Move first parameter address in
addr_listi = &list[i] — Move second parameter address in
a = *addr_i — Move first parameter value in
b = *addr_listi — Move second parameter value in
i = b — Sets i to 5
*addr_i = a — Move first parameter value out
*addr_listi = b — Move second parameter value out

In this case, the assignment to the global i in fun changes its value from 3 to
5 , but the copy back of the first formal parameter (the second to last line in the
example) sets it back to 3. The important observation here is that if pass-by-
reference is used, the result is that the copy back is not part of the semantics,
and i remains 5. Also note that because the address of the second parameter is
computed at the beginning of fun, any change to the global i has no effect on
the address used at the end to return the value of list[i].

9.6 Parameters That Are Subprograms


In programming, a number of situations occur that are most conveniently
handled if subprogram names can be sent as parameters to other subprograms.
One common example of these occurs when a subprogram must sample some
mathematical function. For example, a subprogram that does numerical inte-
gration estimates the area under the graph of a function by sampling the func-
tion at a number of different points. When such a subprogram is written, it
should be usable for any given function; it should not need to be rewritten for
every function that must be integrated. It is therefore natural that the name of
a program function that evaluates the mathematical function to be integrated
be sent to the integrating subprogram as a parameter.
Although the idea is natural and seemingly simple, the details of how it
works can be confusing. If only the transmission of the subprogram code was
necessary, it could be done by passing a single pointer. However, two compli-
cations arise.
First, there is the matter of type checking the parameters of the activations
of the subprogram that was passed as a parameter. In C and C++, functions
cannot be passed as parameters, but pointers to functions can. The type of a
pointer to a function includes the function’s protocol. Because the protocol
includes all parameter types, such parameters can be completely type checked.
Free download pdf