2
votes

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
can't see from this code, nothing to do with question though. PS test for 1 to 4999 outside of the function,doing it inside and then asking for another if it's not is very very very bad. Functions should do one thing. - Tony Hopkinson
@Tony This is what I ended up doing, creating an auxiliary method to test, solved the problem. - gestalt
Makes sense breaking a piece of code that does too many things up into single purpose functions often uncovers bugs and weaknesses in an implementation. Make it a habit, it will stand you in good stead. If there's stuuf that can be optimised by inlining, the compiler will do that for you. Always go for comprehensibility first. - Tony Hopkinson

1 Answers

2
votes

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.