Concepts of Programming Languages

(Sean Pound) #1
9.2 Fundamentals of Subprograms 393

The exemptions formal parameter can be absent in a call to compute_pay;
when it is, the value 1 is used. No comma is included for an absent actual
parameter in a Python call, because the only value of such a comma would be
to indicate the position of the next parameter, which in this case is not neces-
sary because all actual parameters after an absent actual parameter must be
keyworded. For example, consider the following call:


pay = compute_pay(20000.0, tax_rate = 0.15)


In C++, which does not support keyword parameters, the rules for default
parameters are necessarily different. The default parameters must appear last,
because parameters are positionally associated. Once a default parameter is
omitted in a call, all remaining formal parameters must have default values.
A C++ function header for the compute_pay function can be written as
follows:


float compute_pay(float income, float tax_rate,
int exemptions = 1)


Notice that the parameters are rearranged so that the one with the default value
is last. An example call to the C++ compute_pay function is


pay = compute_pay(20000.0, 0.15);


In most languages that do not have default values for formal parameters,
the number of actual parameters in a call must match the number of formal
parameters in the subprogram definition header. However, in C, C++, Perl,
JavaScript, and Lua this is not required. When there are fewer actual param-
eters in a call than formal parameters in a function definition, it is the program-
mer’s responsibility to ensure that the parameter correspondence, which is
always positional, and the subprogram execution are sensible.
Although this design, which allows a variable number of parameters, is
clearly prone to error, it is also sometimes convenient. For example, the printf
function of C can print any number of items (data values and/or literals).
C# allows methods to accept a variable number of parameters, as long as
they are of the same type. The method specifies its formal parameter with the
params modifier. The call can send either an array or a list of expressions,
whose values are placed in an array by the compiler and provided to the called
method. For example, consider the following method:


public void DisplayList(params int[] list) {
foreach (int next in list) {
Console.WriteLine("Next value {0}", next);
}
}

Free download pdf