Forward declarations are closely related to the Delphi language rule that everything has to be declared before it can be used. The following application works properly because the MyAbs function is declared before the procedure that uses it.
function MyAbs(X: Integer): Integer; begin if X > 0 then Result := X else Result := -X; end; procedure MyWriteAbsolute(X: Integer); begin WriteLn('Abs = ', MyAbs(X)); end;
But, if we declare the MyWriteAbsolute procedure before the MyAbs function, the application will no longer compile because the procedure can no longer see the MyAbs function. In large units (actually in any unit), constantly changing the procedure declaration order is neither smart nor useful.
Forward declarations help us bend the "declare before you use" rule. Forward declarations are actually procedure or function headers followed by the forward directive. Forward declarations should always be written before all other declarations. In this case, we have to make a forward declaration of the MyAbs function. With a forward declaration, the function will be usable even if it's located below all other procedures and functions in the unit.
Listing 5-14: Forward declaration
program Project1; {$APPTYPE CONSOLE} uses SysUtils; function MyAbs(X: Integer): Integer; forward; procedure MyWriteAbsolute(X: Integer); begin WriteLn('Abs = ', MyAbs(X)); end; function MyAbs(X: Integer): Integer; begin if X > 0 then Result := X else Result := -X; end; begin MyWriteAbsolute(-100); ReadLn; end.