As your programs become more advanced, placing all the code in the main program can make the program more difficult to code. Slicing the program into sections can help. These sections are called by many names. The names include: subs, sub-modules, sub-procedures, and procedures. In pascal, these sections of code are called procedures.


The way that the procedures work, is that the main program will call the procedure. Once the procedure is called, the code within the procedure will run. When the procedure is done running the main program will continue with its code.



This example shows a simple program that takes the code to stop the program and puts the code into a procedure.



program ProcedureExample1;


{$mode objfpc}{$H+}


uses

  {$IFDEF UNIX}{$IFDEF UseCThreads}

  cthreads,

  {$ENDIF}{$ENDIF}

  Classes

  { you can add units after this };



procedure StopProgram;

begin

  writeln;

  writeln;

  writeln('Press <Enter> To Quit');

  readln;

end;   {the end of the StopProgram Procedure}


begin   {main program}

  writeln('5 * 5 = ', 5 * 5);

  StopProgram;

end.



The next example uses global and local variables



program Project1;


{$mode objfpc}{$H+}


uses

  {$IFDEF UNIX}{$IFDEF UseCThreads}

  cthreads,

  {$ENDIF}{$ENDIF}

  Classes

  { you can add units after this };

var

  x:integer;


procedure proc1;

begin

  writeln('X In Proc1 = ', x);

end;


procedure proc2;

var

  x:integer;

begin

  x:= 20;

  writeln('X In Proc2 = ' , x);

end;


procedure StopProgram;

begin

  writeln;

  writeln;

  writeln('Press <Enter> To Quit');

  readln();

end;


begin

  x:= 35;

  proc1;

  proc2;

  StopProgram;

end




On your own:

Modify the “Guess My Number” program in Tutorial 7 to use procedures instead of having all of code in the main program.





Video Tutorial: Free Pascal Tutorial 11 - Procedures (7:03)

Previous                   Next