Stepping through Code

Most of the debugging techniques described in this tutorial require you to step through the code a line at a time. In Delphi, to view the next source line, press F7 or select menu item Run > Trace Into. In Lazarus, press F7 or select menu item Run > Step into.

Program CalcFactorial accepts an integer but fails to output its factorial.

program CalcFactorial;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  i  : integer;
  Fact : int64 = 1;
begin
  write('Enter an integer (1-20) to find its factorial. ');
  readln(i);
  while i > 1 do
    Fact := Fact * i;
    dec(i);
  writeln('Factorial: ', Fact);
  readln;
end.

In order to step through the program:

  1. Press F7 four times.
  2. Select the console window.
  3. Type a value such as 5 for i.
  4. Press RETURN.
  5. Press F7.

The following screenshot shows the critical section of code.

Critical code

Critical code

Press F7 once more to see the previous line of code being highlighted:

Error revealed

Error revealed

The dec(i) statement is indented and is intended to be part of the loop. There should be a begin after do and an end after dec(i).

We use program CalcFactorial2 (which contains the same error as program CalcFactorial1) to demonstrate how to run a whole procedure without stepping through each line of its code.

program CalcFactorial2;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  i  : integer;
  Fact : int64 = 1;

procedure Intro;
begin
  writeln('This program should find the factorial');
  writeln('of a number in the range 1-20.');
  writeln('It contains a deliberate error.');
  writeln('This procedure is present as a demonstration');
  writeln('of how you can avoid stepping through each line.');
  writeln('One press of F8 will execute all lines in this');
  writeln('procedure.');
  writeln;
  write('Enter an integer (1-20) to find its factorial. ');
end;

begin
  Intro;
  readln(i);
  while i > 1 do
    Fact := Fact * i;
    dec(i);
  writeln('Factorial: ', Fact);
  readln;
end.

Press F7 twice to highlight procedure Intro then press F8 to execute all the lines in the procedure. Instead of pressing F8, you can select menu item Run > Step over in Delphi or Lazarus.

Programming - a skill for life!

Stepping through code, setting breakpoints, error handling and range checking