Passing strings to and from functions in Pascal III

Passing strings to and from functions in Pascal III

Functions cannot return a string per se because functions cannot return a non-scalar variable, such as a string. Functions can however return the address of a string with the VARiable (VAR) parameter. The pass-by-referenceVAR parameter can pass the address of a string to and from functions and assembly language routines. In contrast, when a value parameter is used, the value of the parameter is passed (See pp.87-90, Apple III Pascal Programmer's Manual, Volume 1). Listed below is an example of passing a string to and from a function. A procedure could have been used similarly since parameter-passing rules are the same for procedures as for functions. The value returned by the function is also used to check the success of the function. This check is a good programming convention for functions.
PROGRAM PASS;

VAR I: INTEGER;
  ST1; STRING;
  TABLE: ARRAY [0..50] OF STRING (* For this program to run, *)
                                 (* TABLE must be initialized*)
                                 (* prior to calling DOIT.   *)

  FUNCTION DOIT (VAR ST2; STRING; INDEX: INTEGER):BOOLEAN;
              (* VAR designates ST2 as a VARiable parameter.*)
  BEGIN
    DOIT := TRUE;
    IF LENGTH(TABLE [INDEX]) = 0 THEN (*DOIT returns false if *)
      DOIT := FALSE                   (*the given entry(INDEX)*)
    ELSE ST2 := TABLE [INDEX]         (*in the table is null. *)
  END;                                (*ELSE, IT RETURNS TRUE.*)

BEGIN
  FOR I := 0 TO 50 DO
  BEGIN                       (* ST1 should be null unless *)
    ST1:= '';                 (* DOIT alters it.           *)
    IF DOIT(ST1,I) THEN       (* If the array entry is not *)
      WRITELN(ST1)            (* null, print the string.   *)
  END;  (* FOR *)
END.


Notes:
1. An individual element of a packed variable cannot be supplied as the actual parameter.  See page 90 of the Apple III Pascal Programmer's Manual, Volume 1.

2. The addresses of strings are ALWAYS passed to the procedure or function, whether the string is a VARiable parameter or a value parameter.  Declaring the string parameter to be a VARiable parameter avoids coping the entire valueof the string to the function and attendant lowering of memory and performance. Bear in mind that, it is generally good programming technique to use value parameters wherever possible for maximum "decoupling" of function and calling program.