When a subprogram is to be invoked, it must have been declared somewhere in the hierarchy of blocks within the standalone program, but prior to where it is invoked. In other words, when scanning the SPL code from beginning to end, the subprogram declaration must be found before its invocation.
However, there is a method of constructing the SPL code so that the full declaration of the subprogram (that is, the optional declaration section, mandatory executable section, and optional exception section of the subprogram) appears in the SPL code after the point in the code where it is invoked.
This is accomplished by inserting a forward declaration in the SPL code prior to its invocation. The forward declaration is the specification of a subprocedure or subfunction name, formal parameters, and return type if it is a subfunction.
The full subprogram specification consisting of the optional declaration section, the executable section, and the optional exception section must be specified in the same declaration section as the forward declaration, but may appear following other subprogram declarations that invoke this subprogram with the forward declaration.
The following example shows the typical usage of a forward declaration, which is when two subprograms invoke each other:
DECLARE FUNCTION add_one ( p_add IN NUMBER ) RETURN NUMBER; FUNCTION test_max ( p_test IN NUMBER) RETURN NUMBER IS BEGIN IF p_test < 5 THEN RETURN add_one(p_test); END IF; DBMS_OUTPUT.PUT('Final value is '); RETURN p_test; END; FUNCTION add_one ( p_add IN NUMBER) RETURN NUMBER IS BEGIN DBMS_OUTPUT.PUT_LINE('Increase by 1'); RETURN test_max(p_add + 1); END; BEGIN DBMS_OUTPUT.PUT_LINE(test_max(3)); END;
Subfunction test_max invokes subfunction add_one, which also invokes subfunction test_max. Therefore, a forward declaration is required for one of the subprograms, which is implemented for add_one at the beginning of the anonymous block declaration section.
The following output is generated by the anonymous block:
Increase by 1 Increase by 1 Final value is 5