St0ne
St0ne

Reputation: 47

pascal illegal qualifier error when calling function from a procedure

function classes(o:integer): String;
var allclasses : array[1..7] of String;
begin
    allclasses[1]:= 'class1';
    allclasses[2]:= 'class2';
    allclasses[3]:= 'class3';
    allclasses[4]:= 'class4';
    allclasses[5]:= 'class5';
    allclasses[6]:= 'class6';
    allclasses[7]:= 'class7';
    classes := allclasses[o];
end;

Above you can see a function, which should receive an integer and give a result of string that was stored in array.

procedure loadthis(chosen : string);
var f: text;
    i : integer;
begin
    Assign(f, 'files\'+chosen+'.txt');
    Reset(f);
    ReadLn(f, i);
    MyChar.clas := classes[i];
end;

When this procedure is called, it calls a "classes" function. Pleae note that Mychar ir a global variable.

begin
    loadthis(FileName);
    ReadLn;
    Readln
end.

Ant this is the main program, which calls "loadthis" procedure.

I Have no idea whats wrong, but I am getting these errors:

Both errors come from this line: MyChar.clas := classes[i];. I have really no idea what is wrong, maybe I can not call a function from a procedure ? Please help.

Upvotes: 3

Views: 9722

Answers (1)

Ken White
Ken White

Reputation: 125689

You're trying to access it as an array index, but it needs to be a function call:

MyChar.clas := classes(i);  { note () instead of [] }

You should probably add some range checking, too. What happens if someone puts 20 in the text file? Your array only has items at indexes 1 through 7, so you'll get a runtime error when you call classes(20) with the out of range value.

(You could probably use a constant array for allclasses to lessen your code as well, but your instructor probably haven't gotten that far yet.)

Given your comment about not having an instructor, here's a suggestion about a better way to handle the function:

function classes(o:integer): String;
const
  allclasses: array[1..7] of string = ('class1', 
                                       'class2',
                                       'class3',
                                       'class4',
                                       'class5',
                                       'class6',
                                       'class7');
begin
  {
    Low() returns the lowest index of the array, and
    High() returns the highest. The if statement makes sure
    that o is between them. It is the range check I mentioned.
  }
  if (o >= Low(allclasses)) and (o <= High(allclasses)) then
    classes := allclasses[o]
  else
    classes := '';
end;

Upvotes: 1

Related Questions