How to enforce immutability to prevent the modification of values in Pascal

3 Answers

0 votes
// Immutable variable using const

program ImmutableConstVar;

{$mode objfpc}

// Const declarations MUST be placed here,
// before the main program block.
const
  x = 10;  // immutable constant

begin
  WriteLn('x = ', x);

   // x := 20;  // ERROR: cannot modify a const // Error: Variable identifier expected
end.



(*
run:

x = 10


*)

 



answered 15 hours ago by avibootz
0 votes
// Immutable function parameters (const parameters)

program ConstParamExample;

{$mode objfpc}

procedure PrintName(const name: string);
begin
  // name is read‑only inside this procedure
  WriteLn('Name: ', name);

  // name := 'Mark';  // ERROR: cannot modify const parameter // Error: Can't assign values to const variable
end;

begin
  PrintName('Mary');
end.



(*
run:

Name: Mary


*)

 



answered 15 hours ago by avibootz
0 votes
// Immutable reference parameters (const reference)

program ConstRefExample;

{$mode objfpc}

type
  TBigRecord = record
    A, B, C: Integer;
  end;

procedure PrintRec(const R: TBigRecord);
begin
  // R is passed by reference but cannot be modified
  WriteLn('A=', R.A, ' B=', R.B, ' C=', R.C);

  // R.A := 10;  // ERROR: cannot modify const reference
end;

var
  Rec: TBigRecord;

begin
  Rec.A := 1;
  Rec.B := 2;
  Rec.C := 3;

  PrintRec(Rec);
end.



(*
run:

A=1 B=2 C=3

*)

 



answered 14 hours ago by avibootz
...