Using Forward Declarations v13
As discussed so far, 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, its optional declaration section, its mandatory executable section, and optional exception section) 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.
Typical usage of a forward declaration is when two subprograms invoke each other as shown by the following:
Subfunction test_max
invokes subfunction add_one
, which also invokes subfunction test_max
, so 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 resulting output from the anonymous block is as follows: