Вопрос

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.
Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top