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.
Yes, values definitely get passed to functions. I promise that
num
really does get passed toconvertNumeral
. Within that function,number
acquires whatever value resides innum
. 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 innum
. The parameter was passed by value, sonumber
stores a copy of the value stored innum
; they're two distinct variables. You can usevar
to pass parameters by reference, if that's what you want.Each recursive call to
convertNumeral
gets a new instance ofnumber
, so changes made tonumber
, if any, will not appear once the function returns to the caller. Each call gets its own versions ofnumber
andj
.