1

We have three programs with procedure.

In proc01:

output: a=22

In proc02:

output: a=16 b=2 c=5

In proc03:

output: a=5

proc01 and 03 are the same. Except that we changed the procedure parameters Why in the proc01 "d" value added, but at proc03, not.

proc02 is another example."d" value not added.

Why????

proc01:

program proc01; 
var
  a,b:integer; 
  procedure test01(var a:integer;b:integer);
  var
    d:integer;
  Begin
    d:=12;
    a:=b+d;
  End; 
Begin
  a:=5;
  b:=10;
  test01(a,b);
  Writeln('a=',a);
  Readln;
End.

proc02:

program proc02;
var
  a,b,c:integer;

procedure test01(var b:integer; a:integer);
var
  d:integer;
Begin
  d:=12;
  a:=b+d;
  b:=a+c;
  c:=c+2;
End;
Begin
     a:=1;
     b:=2;
     c:=3;
     test01(a,b);
     Writeln('a=',a,' b=',b,' c=',c);
     Readln;
End.

proc03:

program proc03;
var
  a,b:integer;

procedure test01(var b:integer;a:integer);
var
  d:integer;
Begin
  d:=12;
  a:=b+d;
End;

Begin
  a:=5;
  b:=10;
  test01(a,b);
  Writeln('a=',a);
  Readln;
End.
naser
  • 171
  • 2
  • 13

2 Answers2

4

likely because in proc03 you are passing value of "a" for the "b" variable and vice versa. See the difference in the signature of test01 in proc01 and proc03 ("a" and "b" are in different order). So in proc3 you are actually feeding the result of "b + d" into the local "a" variable, but into the program's "b" variable, program's "a" variable is not modified. So change the signature of test01 to

procedure test01(var a:integer, b: integer)

to make it work as expected.

In general, I would not recommend to use exact same names here for program's and procedures's variables to prevent similar errors.

Alex

Alex
  • 98
  • 6
  • I know.But I want to know exactly what happens when the value of d can not be added in proc02 and 03 ? – naser Dec 01 '13 at 17:02
  • 2
    +1. Very nice catch about the reversed order of the two arguments (called with `a` and `b`, but receives `b` and `a` and `b` is the one that's `var`, meaning it changes the global `a` value. – Ken White Dec 01 '13 at 17:55
  • 2
    @naser: `d` isn't added because it's being added in the procedure to `a`, which is passed by value, so any changes to it are discarded when the procedure ends. Changes made to `b` in the procedure, on the other hand, stay (in the global `a`) after the procedure exits because `b` is passed by reference (with `var`) and not value. See [Blocks and Scopes](http://docwiki.embarcadero.com/RADStudio/XE5/en/Declarations_and_Statements#Blocks_and_Scope) and [Parameters - Delphi](http://docwiki.embarcadero.com/RADStudio/XE5/en/Parameters_%28Delphi%29). The same rules apply for Pascal. – Ken White Dec 01 '13 at 17:59
  • @ken-white : ya ya.You are right.But what happened in proc02? – naser Dec 02 '13 at 05:11
2

In proc 02 and 03 a parameter is passed by value and not by reference
So when you assign any value to a it will modify only local copy and will not modify passed variable

VitaliyG
  • 1,837
  • 1
  • 11
  • 11