Jump to content
Hostul a fost schimbat. Daca vedeti serverul offline readaugati rpg.b-zone.ro sau 141.95.124.78:7777 in clientul de sa-mp ×

[PASCAL] Calling by reference


CouldnoT
 Share

Recommended Posts

Calling by reference

 

If we add the var keyword to the declaration of DoSomething's x parameter, things will be different now:

 

procedure DoSomething(var x: Integer);
begin
 x:= x * 2;
 Writeln('From inside procedure: x = ', x);
end;
// main
var
 MyNumber: Integer;
begin
 MyNumber:= 5;
 DoSomething(MyNumber);
 Writeln('From main program, MyNumber = ', MyNumber);
 Writeln('Press enter key to close');
 Readln;
end.

 

This time MyNumber's value will be changed according to x, which means they are sharing the same memory location. We should pass a variable (not a constant) to the procedure this time, using the same type: if the parameter is declared as Byte, then MyNumber should be declared as Byte; if it is Integer, then it should be Integer. The next example will generate an error when calling DoSomething, which requires a variable for its parameter:

 

  DoSomething(5);

 

In calling by value, the previous code could be used, because it cares only about having a value passed as its parameter, and 5 is a value, but in calling by reference the program cares about having a variable passed as its parameter and then acts on its value. In the next example, we will pass two variables, and then the procedure will swap their values:

 

procedure SwapNumbers(var x, y: Integer);
var
 Temp: Integer;
begin
 Temp:= x;
 x:= y;
 y:= Temp;
end;
// main
var
 A, B: Integer;
begin
 Write('Please input value for A: ');
 Readln(A);
 Write('Please input value for B: ');
 Readln(B);
 SwapNumbers(A, B);
 Writeln('A = ', A, ', and B = ', B);
 Writeln('Press enter key to close');
 Readln;
end. 

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.