Your First Program & Program Structure
3.1 Hello, World (Free Pascal)
Save as hello.pas:
Compile and run:
program Hello;
{$mode objfpc}{$H+}
begin
Writeln('Hello, World!');
end.fpc hello.pas
./hello # Linux/macOS
hello.exe # Windows3.2 Hello, World (Delphi console)
program Hello;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
begin
try
Writeln('Hello, World!');
Readln; // keep the console window open when run from the IDE
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.3.3 Anatomy of a program
program Name; Name must be a valid identifier; ISO Pascal allows program Name(input, output); lists units (modules); System is always used implicitly label, const, type, var declaration sections; ISO Pascal requires this order, FPC/Delphi allow any order and repetition procedure and function declarations begin... end. main program block — the only end followed by a period
program Anatomy; // 1. program heading (optional in FPC/Delphi, but conventional)
{$mode objfpc}{$H+} // 2. compiler directives
uses // 3. uses clause: units this program needs
SysUtils, Math;
const // 4. declaration sections, in any order and repeatable
MaxItems = 10;
type
TScore = 0..100;
var
Total: Integer;
Score: TScore;
procedure ShowTotal; // 5. routines
begin
Writeln('Total = ', Total);
end;
begin // 6. main block
Total := 0;
for Score := 1 to MaxItems do
Total := Total + Score;
ShowTotal;
Writeln('Max of 3 and 7: ', Max(3, 7));
end. // 7. final "end" followed by a period3.4 Statements and semicolons
In Pascal, the semicolon separates statements; it does not terminate them. That is why the last statement before end does not need one (an extra one creates a harmless empty statement):
The one place where a semicolon is a real error is before else in an if statement:
begin
A := 1;
B := 2; // the ';' here is optional
end;if X > 0 then
Writeln('positive') // no semicolon here!
else
Writeln('not positive');3.5 Compound statements
begin ... end groups several statements into one, wherever a single statement is expected:
if X > 0 then
begin
Writeln('positive');
Inc(Count);
end;