Functions

Top  Previous  Next

The "return" statement is also used to "return" a value from a subroutine to the calling routine. A subroutine that returns a value is called a function. A function is similar to a procedure except that it returns a value and is used as a value. A procedure call is a statement, but a function call represents a value and is therefore a factor. The general form of a function is:

 

        function TYPE NAME(COMMENT);

        DECLARATIONS;

        STATEMENT;

 

Since all factors must be distinguished as either integers or reals, the function declaration includes a type specifier. This specifier is either "integer", "real", or none. If the type is not specified (none), the function defaults to "integer".

 

The value to be returned by the function is placed immediately following the "return" command. The general form is:

 

        return EXPRESSION;

 

Here is an example of how a function is used:

 

        integer X, Y;

 

                function integer Increment(A);

                integer A;

                begin

                return A + 1;

                end;

 

        begin

        X:= 3;

        Y:= Increment(X);       \Function call

        end;

 

This function increments a value. When the function is called, the value in X is sent to it. This value is incremented and passed back to the caller by the "return" statement. The result (4) is then stored into the variable Y.

 

Here is an example of a function that returns a real value:

 

        real Angle;

 

                func real Deg(X);

                real X;

                return 57.2957795 * X;

 

        begin

        Angle:= Deg(3.141592654);

        end;

 

This function converts radians to degrees. Angle gets 180.0.

 

Here is an example of a function that returns a boolean:

 

        code ChIn=7, ChOut=8, Text=12, OpenI=13;

        integer Ch;

 

                function Affirmative;

                begin

                OpenI(0);

                return ChIn(0) = ^y;

                end;

 

        begin

        Text(0, "Do you want to see the ASCII character set? ");

        if Affirmative then for Ch:= $20, $7E do ChOut(0, Ch);

        end;

 

This function returns "true" if the first character typed on the keyboard is a "y" (as in "yes"), otherwise it returns "false". The OpenI (OPEN Input) intrinsic discards any characters that might already be in the keyboard's buffer, thus assuring that the intended character is used.

 

If a "return" is used in the main (highest-level) procedure, it has the same effect as an "exit" statement. If an expression follows such a "return", it also has the same effect as an expression following an "exit" statement. (See: Exit.)