We can define our own addition function,
add, in a very similar way to the definition of a procedure.
PROC main() DEF sum sum:=12+79 WriteF('Using +, sum is \d\n', sum) sum:=add(12,79) WriteF('Using add, sum is \d\n', sum) ENDPROC PROC add(x, y) DEF s s:=x+y ENDPROC s
This should generate the following output:
Using +, sum is 91 Using add, sum is 91
In the procedure
add the value
s is returned using the
The value returned from
add can be used in expressions, just like any other value.
You do this by writing the procedure call where you want the value to be.
In the above example we wanted the value to be assigned to
sum so we wrote the call to
add on the right-hand side of the assignment.
Notice the similarities between the uses of
add(a,b) can be used in exactly the same places that
a+b can (more precisely, it can be used anywhere
(a+b) can be used).
RETURN keyword can also be used to return values from a procedure.
ENDPROC method is used then the value is returned when the procedure reaches the end of its code.
However, if the
RETURN method is used the value is returned immediately at that point and no more of the procedure's code is executed.
Here's the same example using
PROC add(x, y) DEF s s:=x+y RETURN s ENDPROC
The only difference is that you can write
RETURN anywhere in the code part of a procedure and it finishes the execution of the procedure at that point (rather than execution finishing when it reaches the end of the code).
In fact, you can use
RETURN in the
main procedure to prematurely finish the execution of a program.
Here's a slightly more complicated use of
PROC limitedadd(x,y) IF x>10000 RETURN 10000 ELSEIF x<-10000 RETURN -10000 ELSE RETURN x+y ENDIF /* The following code is redundant */ x:=1 IF x=1 THEN RETURN 9999 ELSE RETURN -9999 ENDPROC
This function checks to see if
x is greater than 10,000 or less than -10,000, and if it is a limited value is returned (which is generally not the correct sum!).
x is between -10,000 and 10,000 the correct answer is returned.
The lines after the first
IF block will never get executed because execution will have finished at one of the
Those lines are therefore just a waste of compiler time and can safely be omitted (as the comment suggests).
If no value is given with the
RETURN keyword then zero is returned.
Therefore, all procedures are actually functions (and the terms procedure and function will tend to be used interchangeably).
So, what happens to the value when you write a procedure call on a line by itself, not in an expression?
Well, as we will see, the value is simply discarded (see 10.1 Turning an Expression into a Statement).
This is what happened in the previous examples when we called the procedures
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.