Sometimes a procedure (or function) will quite often be called with a particular (constant) value for one of its parameters, and it might be nice if you didn't have to fill this value in all the time. Luckily, E allows you to define default values for a procedure's parameters when you define the procedure. You can then just leave out that parameter when you call the procedure and it will default to the value you defined for it. Here's a simple example:
PROC play(track=1) WriteF('Starting to play track \d\n', track) /* Rest of the code... */ ENDPROC PROC main() play(1) -> Start playing from track 1 play(6) -> Start playing from track 6 play() -> Start playing from track 1 ENDPROC
This is an outline of a program to control something like a CD player.
play procedure has one parameter,
track, which represents the first track that should be played.
Often, though, you just tell the CD player to play, and don't specify a particular track.
In this case, play starts from the first track.
This is exactly what happens in the example above: the
track parameter has a default value of 1 defined for it (the
=1 in the definition of the
play procedure), and the third call to
main does not specify a value for
track, so the default value is used.
There are two constraints on the use of default arguments:
On the other hand, these definitions are all illegal:PROC fred(x, y, z) IS x+y+z -> No defaults PROC fred(x, y, z=1) IS x+y+z -> z defaults to 1 PROC fred(x, y=23, z=1) IS x+y+z -> y and z have defaults PROC fred(x=9, y=23, z=1) IS x+y+z -> All have defaults
PROC fred(x, y=23, z) IS x+y+z -> Illegal: no z default PROC fred(x=9, y, z=1) IS x+y+z -> Illegal: no y default
In this example, you cannot leave out thePROC fred(x, y=23, z=1) WriteF('x is \d, y is \d, z is \d\n', x, y, z) ENDPROC PROC main() fred(2, 3, 4) -> No defaults used fred(2, 3) -> z defaults to 1 fred(2) -> y and z default fred() -> Illegal: x has no default ENDPROC
yparameter in a call to
fredwithout leaving out the
zparameter as well. To make
yhave its default value and
zsome value other than its default you need to supply the
yvalue explicitly in the call:
fred(2, 23, 9) -> Need to supply 23 for y
These constraints are necessary in order to make procedure calls unambiguous. Consider a three-parameter procedure with default values for two of the parameters. If it is called with only two parameters then, without these constraints, it would not be clear which two parameters had been supplied and which had not. If, however, the procedure were defined and called according to these constraints, then it must be the third parameter that needs to be defaulted (and the two parameters with default values must be the last two).
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.