We have seen a procedure as a named block of code which does some operation.
On entry, it is given some values to work with
On exit, it has some observable effect
Note the parameter modes here:
In such situations, instead of writing the subprogram as a procedure we should write it as a function.
Named block of code
Function definition: like procedure, except:
------------------------------------------ -- abs: absolute value ------------------------------------------ function abs (x : in INTEGER) return INTEGER is begin -- abs if x >= 0 then return x; else return -x; end if; end abs;
Function calls appear in expressions
y := abs (x); y := 10 * abs (-4); y := abs (10 - abs (x));
abs
as a procedure:
------------------------------------------ -- abs: absolute value ------------------------------------------ procedure abs ( x : in INTEGER; -- argument y : out INTEGER -- abs(argument) ) is begin -- abs if x >= 0 then y := x; else y := -x; end if; end abs;
The logic is similar. The difference is that no return statements appear in the procedure. Instead, there is an extra parameter (an out parameter), and the value to be returned is simply assigned to the out parameter.
The procedure calls that would correspond to the example function calls above are:
abs (x,y); -- y := abs(x); abs (-4, temp); -- y := 10 * abs(-4); y := 10 * temp; abs (x, temp); -- y := abs (10 - abs(x)); temp := 10 - temp; abs (temp, y);
The function implementation is more natural.
Use functions when you can.
function abs (x : in INTEGER) return INTEGER is a : INTEGER; begin -- abs if x >= 0 then a := x; else a := -x; end if; return a; end abs;
Some functions need more than one argument:
------------------------------------------ -- determine the larger of two arguments ------------------------------------------ function max (x, y : in INTEGER) return INTEGER is begin -- max if x >= y then return x; else return y; end if; end max;
The return statement can include an expression, not just a variable name. Sometimes this means that the body of the function can even be just a single return statement:
------------------------------------------ -- cube: cube of argument ------------------------------------------ function cube (x : in INTEGER) return INTEGER is begin -- cube return x*x*x; end cube; a := cube(3); b := cube (max (x, y));