Does Pascal support passing parameters to function

2019-07-11 13:21发布

I'm new to Pascal and I am trying to write a simple program, but an having trouble passing values between functions. This is a small piece of what I have:

program numberConverter;

const
    maxValue = 4999;
    minValue = 1;

var num: integer;

function convertNumeral(number: integer):string;
var j: integer;
begin
if ((number < minValue) OR (number > maxValue)) then
    begin
    writeln(number);
    writeln('The number you enter must be between 1 and 4999. Please try again:');
    read(j);
    convertNumeral := convertNumeral(j);
    end
else 
 if (number >= 1000) then
convertNumeral := 'M' + convertNumeral(number -1000)
{more code here, left it out for space}
end;

begin
    writeln;
    writeln('Enter an integer between 1 and 4999 to be converted:');
    read(num);
    writeln;
    writeln(num);
    writeln(convertNumeral(num));
end.

My problem is that the value from the writeln(converNumeral(num)), mainly 'num', does not get passed to the convertNumeral function and was wondering if Pascal even does this. I figure its because I haven't declared number to be a variable, but when I do I get a compile error that it can't complete the second if statement. Thanks for your time.

1条回答
等我变得足够好
2楼-- · 2019-07-11 13:38

Yes, values definitely get passed to functions. I promise that num really does get passed to convertNumeral. Within that function, number acquires whatever value resides in num. Perhaps there's a problem with how you're observing the behavior of your program.

Changes you make to number, if any, will not be reflected in num. The parameter was passed by value, so number stores a copy of the value stored in num; they're two distinct variables. You can use var to pass parameters by reference, if that's what you want.

Each recursive call to convertNumeral gets a new instance of number, so changes made to number, if any, will not appear once the function returns to the caller. Each call gets its own versions of number and j.

查看更多
登录 后发表回答