A r t i c l e s
Navigation

Note: This site is
a bit older, personal views
may have changed.

M a i n P a g e

D i r e c t o r y

Using Initialized Records


Initialized records are very handy, especially when you do not wish to set the address of a procedure in a record in your code. Initialized records help keep the code cleaner. Initialized records in the VAR declaration means you do not have to initialize your record in the code or in the initialization section of a unit file.
program Project1;

{$mode objfpc}{$H+}

type
  TTestRecord = record
    number1: integer;
    number2: integer;
    text1: string;
    text2: string;
    proc1: procedure;
  end;

procedure procedure1;
begin
  writeln('And this is procedure1');
end;

var
  TestRecord: TTestRecord = (
    number1: 1;
    number2: 2;
    text1: 'testing1';
    text2: 'test2';
    proc1: @procedure1;
  );

begin
  // let's modify the record's values
  writeln(TestRecord.number1);
  writeln(TestRecord.number2);
  writeln(TestRecord.text1);
  writeln(TestRecord.text2);
  // fire off the procedure
  TestRecord.proc1;
  readln;
end.

Now let's take the program one step further, and look at how we modify our records. In other words, the initialized record is obviously not a CONSTANT, it is a VAR of course. Yes, you can modify your initialized record.
program Project1;

{$mode objfpc}{$H+}

type
  TTestRecord = record
    number1: integer;
    number2: integer;
    text1: string;
    text2: string;
    proc1: procedure;
  end;

procedure procedure1;
begin
  writeln('And this is procedure1');
end;

var
  TestRecord: TTestRecord = (
    number1: 1;
    number2: 2;
    text1: 'testing1';
    text2: 'test2';
    proc1: @procedure1;
  );

begin

  // let's display the initialized record
  writeln(TestRecord.number1);
  writeln(TestRecord.number2);
  writeln(TestRecord.text1);
  writeln(TestRecord.text2);
  TestRecord.proc1;
  writeln('press ENTER to continue...');
  readln;
  writeln;
 
  // let's modify the record's values
  TestRecord.number1:= 111 ;
  TestRecord.number2:= 222 ;
  TestRecord.text1:= 'the new text 1' ;
  TestRecord.text2:= 'the new text 2' ;

  // let's display the new record values
  writeln(TestRecord.number1);
  writeln(TestRecord.number2);
  writeln(TestRecord.text1);
  writeln(TestRecord.text2);

  writeln('press ENTER to exit...');
  readln;
 
end.


About
This site is about programming and other things.
_ _ _