开发者

call by value-result in Pascal

开发者 https://www.devze.com 2023-01-03 17:41 出处:网络
How can i simulate calling by value-result in this example. Without adding variables and without change a variable name.?

How can i simulate calling by value-result in this example. Without adding variables and without change a variable name.?

Program one;
    var
      x:integer;
    Function two():integer;
        begin
           x:=x+1;
           two:=x;
        end;
    Procedure three(x:integer);
       begin
          x:=x+5;
          x:=tw开发者_StackOverflowo();
       end;
begin
x:=8;
three(x);
write(x);
end.


If it's homework, I don't think you will have to try var y hard to find the answer.

EDIT: The comment below is correct - maybe I was leading you up the wrong path - it's probably best to return to where we were and start from there.


Do to two() what three() already does.


It's hard to make out something of the question in its present form.

However, the question seems to make some sense if we suppose that the OP is asking how to emulate calling by reference (not by value) in the example code.

So... The actual code passes the parameter to three() by value. three() seems to be trying to store the value to the global variable, before calling two() which, in its turn, changes the global.

But the global variable is actually being used to pass the value, and so the trick is that after passing the global by value to three() the global will end up changed, as if it were passed by reference.

Only there's a little question (which seems to constitute the whole problem): how to address the global from within three() since the parameter's name is the same as the global's?

I don't know what version of Pascal is supposed to run this code, but if the compiler is compatible with TP/Delphi family and if the var names must be left unchanged, then I would try the only way I am aware of so far: one.x. Specifically, this line in three()'s implementation

x:=x+5;

I would change to

one.x:=x+5;

So, the global here receives the parameter value increased by 5 and calls two(), and two() changes the global once again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号