Porting C to Pascal
last modified November 19, 2026 Free Pascal 3.2.2
C and Pascal share a machine model: pointers hold addresses, arrays are contiguous, structures are laid out field by field, and memory can be allocated by hand. The differences are in the details: Pascal strings carry a length, array bounds are part of the type, and the preprocessor is replaced by compiler directives. This article maps the types, ports a structure and a sorting routine, compares string and memory handling, and lists the pitfalls that produce code which compiles but behaves differently.
Types and sizes
C types are deliberately vague about size: int is at least 16
bits, long is at least 32, and the actual width depends on the
platform. Pascal has the same problem in its older dialects, which is why the
ctypes unit provides exact aliases for interfacing with C. Use
them whenever a value crosses the boundary or a binary layout matters.
program types;
{$mode objfpc}{$H+}
uses
ctypes;
begin
WriteLn('cint: ', SizeOf(cint));
WriteLn('clong: ', SizeOf(clong));
WriteLn('csize_t: ', SizeOf(csize_t));
WriteLn('cdouble: ', SizeOf(cdouble));
WriteLn('Pointer: ', SizeOf(Pointer));
WriteLn('SizeInt: ', SizeOf(SizeInt));
WriteLn('Char: ', SizeOf(Char));
end.
On this 64-bit Linux system clong is 8 bytes, following the LP64
model; on 64-bit Windows the same C long is 4 bytes. That is
exactly why LongInt should not be used for a C long
in portable code. SizeInt and PtrInt follow the
pointer width, and csize_t is the unsigned type used for sizes
and indexes.
$ fpc -gl types.pas $ ./types cint: 4 clong: 8 csize_t: 8 cdouble: 8 Pointer: 8 SizeInt: 8 Char: 1
Structures and pointers
A C structure becomes a Pascal record with the same fields. The C
char name[16] becomes array[0..15] of Char, not a
Pascal string: a string is a managed pointer, while the array is
inline storage of exactly 16 bytes.
typedef struct {
char name[16];
int score;
} Player;
void boost(Player *p, int amount)
{
p->score += amount;
}
The Pascal translation keeps the field order and uses cint for the
score. StrCopy writes a NUL-terminated name into the character
array, and Inc(P^.Score, Amount) is the direct equivalent of
p->score += amount.
program player;
{$mode objfpc}{$H+}
uses
SysUtils, ctypes;
type
TPlayer = record
Name: array[0..15] of Char;
Score: cint;
end;
PPlayer = ^TPlayer;
procedure Boost(P: PPlayer; Amount: cint);
begin
Inc(P^.Score, Amount);
end;
var
P: TPlayer;
begin
StrCopy(P.Name, 'Alice');
P.Score := 100;
Boost(@P, 25);
WriteLn('size: ', SizeOf(TPlayer));
WriteLn('name: ', P.Name);
WriteLn('score: ', P.Score);
end.
The record is 20 bytes: 16 for the name and 4 for the score, with no padding
because the alignment of cint is 4. A C compiler produces the same
size for the same declaration. If the C structure uses #pragma pack
or a packed attribute, mirror it with a packed record and verify
the size on both sides.
$ fpc -gl player.pas $ ./player size: 20 name: Alice score: 125
Strings
A C string is a pointer to bytes terminated by a zero. A Pascal
string is a managed value with a length, so Length is
constant time and the text may contain a zero byte. The C view is available
through PChar: the cast PChar(S) produces a
NUL-terminated copy that is valid while S is alive.
program cport;
{$mode objfpc}{$H+}
uses
SysUtils;
var
S: string;
I, VowelCount: Integer;
begin
S := 'Porting C code to Pascal';
VowelCount := 0;
for I := 1 to Length(S) do
if UpCase(S[I]) in ['A', 'E', 'I', 'O', 'U'] then
Inc(VowelCount);
WriteLn('length: ', Length(S));
WriteLn('vowels: ', VowelCount);
WriteLn('upper: ', UpperCase(S));
end.
The C loop would start at 0 and stop before
strlen(S); the Pascal loop starts at 1 and ends at
Length(S), because string indexes are 1-based. The set
['A', 'E', 'I', 'O', 'U'] replaces the chain of comparisons in a
C switch. UpCase and UpperCase are not
locale-aware for non-ASCII text; use UTF8UpperCase from
LazUTF8 in a Lazarus project for that.
$ fpc -gl cport.pas $ ./cport length: 24 vowels: 7 upper: PORTING C CODE TO PASCAL
Arrays and a sorting routine
A C array parameter decays to a pointer and carries no length, so the caller
passes the count separately. A Pascal array parameter can carry its bounds, or
it can be an open array that receives the length automatically. The bubble sort
below is a direct port: the indexes move from 0 to N - 1 in both
languages, but the Pascal array is declared with those bounds.
void bubble(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
The Pascal version uses a const for the size, a static array with
the same bounds, and a temporary variable declared at the top of the program.
The swap is three assignments in both languages.
program bubble;
{$mode objfpc}{$H+}
const
N = 8;
var
A: array[0..N - 1] of Integer = (5, 2, 9, 1, 7, 3, 8, 4);
I, J, T: Integer;
begin
for I := 0 to N - 2 do
for J := 0 to N - 2 - I do
if A[J] > A[J + 1] then
begin
T := A[J];
A[J] := A[J + 1];
A[J + 1] := T;
end;
for I := 0 to N - 1 do
Write(A[I], ' ');
WriteLn;
end.
Pascal's for loop includes both bounds, so 0 to N - 2
is the same as C's i < n - 1. The loop variable cannot be
changed inside the body, and after the loop it keeps its last value rather than
becoming undefined as in C. The array initializer in the declaration is a
Pascal extension that is convenient for examples but not for large data.
$ fpc -gl bubble.pas $ ./bubble 1 2 3 4 5 7 8 9
Manual memory
malloc and free map to GetMem and
FreeMem. Both take a byte count, both return raw memory that is
not initialized, and both require the programmer to release it. For a single
typed value, New and Dispose are safer because they
know the type and finalize managed fields.
program cma;
{$mode objfpc}{$H+}
var
A: ^Integer;
I: Integer;
begin
GetMem(A, 5 * SizeOf(Integer));
for I := 0 to 4 do
(A + I)^ := (I + 1) * 10;
for I := 0 to 4 do
Write((A + I)^, ' ');
WriteLn;
FreeMem(A);
end.
The pointer arithmetic is scaled by SizeOf(Integer), exactly as in
C. There is no bounds check, no zeroing, and no automatic cleanup. If the block
holds a managed type such as a string, GetMem leaves it
uninitialized and FreeMem does not release it; use a dynamic array
or a record allocated with New instead.
$ fpc -gl cma.pas $ ./cma 10 20 30 40 50
Preprocessor directives
C's #define becomes a Pascal const, and
#ifdef becomes {$IFDEF}. The directive is evaluated
at compile time and can select a different body for a debug build. Unlike the C
preprocessor, Pascal directives are part of the compiler and cannot define
arbitrary text macros.
program buildinfo;
{$mode objfpc}{$H+}
begin
{$IFDEF DEBUG}
WriteLn('debug build');
{$ELSE}
WriteLn('release build');
{$ENDIF}
end.
The symbol is defined with -dDEBUG on the command line or with
{$DEFINE DEBUG} in the source. The same mechanism selects platform
code with {$IFDEF UNIX} or {$IFDEF WINDOWS}, and
{$IF DEFINED(CPU64)} tests a symbol without requiring it to be
undefined elsewhere.
$ fpc -gl buildinfo.pas $ ./buildinfo release build $ fpc -gl -dDEBUG buildinfo.pas $ ./buildinfo debug build
Common pitfalls
The first surprise is integer division. C and Pascal both truncate toward zero,
but Pascal uses div for integers and / only for
reals. Writing 7 / 2 in Pascal produces 3.5, not 3; use
7 div 2 for the C behaviour. The mod operator takes
the sign of the dividend in both languages.
The second is the boolean type. A C int used as a flag is 4 bytes,
while Pascal Boolean is 1 byte and only accepts True
and False. When a C function returns an int flag,
declare it as cint and compare with zero, rather than pretending it
is a Pascal boolean.
The third is pointer and array syntax. Pascal dereferences with ^
and takes an address with @; a struct field is
P^.Field, never P->Field. An array parameter
without a declared size is an open array, which carries its length; a pointer
parameter carries nothing. Choose the one that matches the C signature, and do
not pass a Pascal string where a char * is expected.
Finally, check the structure layout and the calling convention before debugging
a crash. A missing cdecl corrupts the stack on 32-bit Windows, and
a field of the wrong width shifts every field after it. The
C interoperability article shows the
working declarations, and the
compiling and debugging article
shows how to inspect the result.
Source
In this article we mapped C types to ctypes, translated a structure
and a bubble sort, compared C strings with Pascal strings, used
GetMem and FreeMem, and replaced the preprocessor with
compiler directives. The C
interoperability article takes the next step and calls the compiled code.
Author
List all Pascal tutorials.