Hello.

I'm studying Pascal in school atm and have come over a bit of a problem with a program I've been asked to write.

The task is too make a calendar. My calendar uses an array with records too store data about the different days. The program uses a procedure to fill the global array with data.
Here comes the problem, my teacher don't like global variables being used inside procedures or functions.

As I come from a Java background I'm really frustrated over the fact that I can't find any simple way to convert my procedure to a function and return an array.

So I wonder if there is some hidden way to do this or some availabe extension to overcome this problem.

I would really appreciate some help.

You most certainly can return arrays from functions. Here are two ways to solve your problem.

program u;
{$APPTYPE CONSOLE}
uses
  SysUtils;

type
  tPerson = record
    name: string;
    age:  integer;
    end;
  tPeople = array of tPerson;

var people: tPeople;

//procedure getPeople( var result: tPeople );  // Method 1
function getPeople: tPeople;  // Method 2
  var
    s: string;
    i: integer;
  begin
  i := 0;
  repeat
    setLength( result, i+1 );
    write( 'Please enter a name> ' );
    readln( result[ i ].name );
    write( 'Please enter ', result[ i ].name, '''s age> ' );
    readln( result[ i ].age );
    write( 'Are there more (yes/no)? ' );
    readln( s );
    inc( i )
  until upCase( s[ 1 ] ) = 'N'
  end;

begin
// Method 1
//getPeople( people );

// Method 2
people := getPeople;

writeln( 'You entered ', length( people ), ' people.' )
end.

Uncomment the method you want (the procedure/function body was written so that it will work with whichever header you uncomment).

The trick is that everything in Pascal must be strongly typed. Notice how the array itself has a specific type. Oh yeah, this is also a dynamic array...

Hope this helps.

Thanks for your help, this will help me out a lot. I think I've read a simular example earlier somewhere but I had totally forgot about that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.