Modify the dpr file from the previous lesson to the following content
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
program MyProgram;
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 is: ', A + 10);
end;
function MyFunction(const S: string): string;
begin
Result := S + 'strings are automatically managed';
end;
var
X: Single;
begin
WriteLn(MyFunction('Note: '));
MyProcedure(5);
// Division using "/" always makes float result, use "div" for integer division
X := 15 / 5;
WriteLn('X is now: ', X); // scientific notation
WriteLn('X is now: ', X:1:2); // 2 decimal places
end.Code language: PHP (php)
D:\fpcdemo>fpc mydemo.dpr
Free Pascal Compiler version 3.2.2 [2021/05/15] for i386
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling mydemo.dpr
Linking mydemo.exe
20 lines compiled, 0.0 sec, 39248 bytes code, 2484 bytes data
D:\fpcdemo>mydemo
Note: strings are automatically managed
A + 10 is: 15
X is now: 3.000000000E+00
X is now: 3.00
D:\fpcdemo>Code language: CSS (css)

Below is the comment explanation. Non-English text may display garbled characters; you can configure the console to output Chinese text normally.
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
program MyProgram;
// Custom name for the current program. Pascal console programs must start with "program [name];", followed by variable declarations, procedures, and main execution logic.
// No return value: procedure. Procedures and functions only run when called; they do nothing if not invoked.
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 =:', A + 10);
end;
// Has return value: function
function MyFunction(const S: string): string;
begin
Result := S + 'The system automatically manages string memory';
end;
// Object Pascal has no main() function. The outermost begin...end. block acts as the program entry point. This is the main program block below.
var
X: Single; // Single-precision floating-point primitive type
begin
// All executable logic is written here
WriteLn(MyFunction('Hint: '));
MyProcedure(5);
// Slash "/" always produces a floating-point result for division; use "div" for integer division
X := 15 / 5;
WriteLn('X is now:', X); // Automatically outputs in scientific notation
WriteLn('X is now:', X:1:2); // Limit output to 2 decimal places
end. // End with end. (with dot) to mark the end of the entire program;Code language: Delphi (delphi)
Each function and procedure contains a pair of begin and end to mark the start and end of its body, equivalent to curly braces { } in C, C++, Java and similar languages.
WriteLn outputs content to the console. Single quotes ‘ ‘ wrap string literals. WriteLn('A + 10 =:', A + 10); prints the string A + 10 =: followed by the calculated value of A + 10 sequentially.
A program can only have one outermost begin and end. block holding the main logic, which calls other functions and procedures internally.
X := 15 / 5;
WriteLn(‘X is now: ‘, X); // scientific notation
WriteLn(‘X is now: ‘, X:1:2); // 2 decimal places
/ denotes floating-point division, and the quotient is always a float value.
The first two lines are preprocessor directives
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}Code language: PHP (php)
This is a FPC exclusive conditional compilation directive
{$ifdef FPC}: Execute the middle configuration only if the current compiler is Free Pascal{$mode objfpc}: Switch syntax mode to ObjFpc{$H+}: Enable long string (modern auto-managed string type, mandatory){$J-}: Disable typed constants modification (constants cannot be reassigned mid-program for safer code){$endif}: End of conditional block
Purpose: Enable modern syntax only when compiling with FPC; Delphi compiler skips this entire section automatically.
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}Code language: PHP (php)
Cross-platform conditional compilation
MSWINDOWS: Takes effect only under Windows operating system{$apptype CONSOLE}: Mark program as a console application (opens a black terminal window instead of GUI window). This line is ignored when compiling on Linux/macOS.
Core Knowledge Points
stringis a native primitive type; FPC/Delphi manages its memory automatically with no manual release required- procedure: No return value; function: Has return value, stored via built-in
Resultvariable - Two division operators:
/floating-point division;divinteger floor division - Formatted output syntax
variable:totalWidth:decimalPlacesto customize float display - Zero-argument recursive functions must append empty parentheses
()to eliminate ambiguity Exit(value)sets return value and terminates the function early- Functions may be invoked without capturing their return value, used for side effects such as modifying global variables
Function Return Value Rules
- The built-in special variable
Resultstores function return values, read/write just like local variables
function MyFunction(const S: string): string;
begin
Result := S + 'One';
Result := Result + 'Two';
end;
Code language: PHP (php)
- Old syntax allows assigning directly to the function name (
MyFunction := xxx), not recommended due to poor readability; standardize onResult.
C/C++/Java/C# use
=for assignment and==for equality comparison. Pascal reverses this::=for variable assignment, plain=for comparison, matching mathematical notation.Pascal has no
==operator
Replace the previous MyFunction with this version. This function appends “One” then “Two” to the input string passed during invocation.
The final returned string will be: original string + One + Two
Recursive Calls
Zero-argument recursive functions must carry empty parentheses () to distinguish “invoke function” from “read current return value”:
function SumIntegersUntilZero: Integer;
var I: Integer;
begin
ReadLn(I);
Result := I;
if I <> 0 then
Result := Result + SumIntegersUntilZero(); // Recursive call with ()
end;
Code language: JavaScript (javascript)
For zero-argument function SumIntegersUntilZero:
SumIntegersUntilZero()→ Invoke the function, execute recursion, fetch return valueSumIntegersUntilZero→ Reference the internalResultvariable (the function’s own return value)
Code with parentheses removed:
Result := Result + SumIntegersUntilZero;
The compiler interprets this as:
Result := Result + Result;
Equivalent to Result := Result * 2. Recursive logic is completely broken, causing infinite loops and exponentially growing numbers.
In this example, the function recursively calls itself repeatedly until the input value equals zero to exit. It recurses as long as input is non-zero.
Early Exit with Exit
- Parameterless Exit: Exit immediately, return the existing assigned Result value
Exit(value): Directly specify return value and terminate function, equivalent to C’s return x
function AddName(const ExistingNames, NewName: string): string;
begin
if ExistingNames = '' then
Exit(NewName); // Return NewName immediately and end function
Result := ExistingNames + ', ' + NewName;
end;
Code language: PHP (php)
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
program MyProgram;
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 is: ', A + 10);
end;
function AddName(const ExistingNames, NewName: string): string;
begin
if ExistingNames = '' then
Exit(NewName);
Result := ExistingNames + ', ' + NewName;
end;
var
X: Single;
begin
WriteLn(AddName('Tom','Jack'));
WriteLn(AddName('Tom',''));
WriteLn(AddName('','Jack'));
end.Code language: PHP (php)
Functions Called as Procedures (Discard Return Value)
Functions with return values may be executed solely for logic while ignoring their output; suitable for scenarios with side effects (modifying global variables):
var
Count, MyCount: Integer;
function CountMe: Integer;
begin
Inc(Count); // Side effect: increment global variable
Result := Count;
end;
begin
Count := 10;
CountMe; // Discard return value, only execute logic, Count becomes 11
MyCount := CountMe; // Capture return value, Count becomes 12
end.
Code language: PHP (php)
Full working example
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
program MyProgram;
var
Count, MyCount: Integer;
function CountMe: Integer;
begin
Inc(Count);
Result := Count;
end;
begin
Count := 10;
WriteLn(CountMe);
MyCount := CountMe;
WriteLn(MyCount);
end.Code language: PHP (php)
Inc is a built-in standard Pascal (FPC/Delphi) routine that increments a variable by 1.
var is Pascal’s variable declaration keyword, used to define variables.
var
Count, MyCount: Integer;Code language: JavaScript (javascript)
var: Opens the variable declaration section
Count, MyCount: Two variable names
Integer: Integer data type
Variables declared inside var in this example are global variables, accessible by all procedures and functions across the entire program.
Functions, Procedures & Basic Primitive Types