Difference between two procedure

FlamingClaw 1 Tallied Votes 196 Views Share

The arguments are passed by value and by reference

AKJo commented: A very simple, but still enlightning example +2
{Difference between two procedure}
Program Difference;
Uses Crt;
{we have two variables,this will A and B}
Var A,B:Byte;

{By value }
Procedure First(F1,F2:Byte);
   Begin
        F1:=F1+2;
        F2:=F2+2;
   End;{first}

{By reference}   {*}
Procedure Second(Var S1,S2:Byte);
   Begin
        S1:=S1+2;
        S2:=S2+2;
   End;{second}

Begin {main}
     A:=1;
     B:=1;
     WriteLn('A:=',A);
     WriteLn('B:=',B);
     First(A,B);
     WriteLn('After the -First- procedure,the result is: ',A+B);
     {now,call the 'Second'}
     Second(A,B);
     WriteLn('And after the -Second- procedure the result is: ',A+B);
     ReadKey;
End. {main}
{Note that the 'First' procedure won't change the value of 'A' and 'B'}
{they only changed inside the First procedure,and effectless for the}
{global variables of the main program}


{Created By FlamingClaw 2009.03.10}
est69dog 0 Newbie Poster

you must use var if you wanth procedure tasks efect to main program
in 1st you dont use var in procedure and thats why no efect to main

FlamingClaw 98 Posting Pro
...
{By reference}   {*}
Procedure Second(Var S1,S2:Byte);
   Begin
        S1:=S1+2;
        S2:=S2+2;
   End;{second}
...
...

This is the second procedure in my example.Its arguments accepts only variables,cause the second procedure make changes on these variables' memory addresses.

CMPITG 0 Newbie Poster

Those are technically called passed by value and passed by reference, corresponding to your program.

  • With "passed by value", your passed variables remain the same no matter how you change it in your local scope (functions, procedures, block code). In this case, it's F1 and F2 .
  • With "passed by reference", every change you made to the local variables would be applied to your passed variables. In this case, it's S1 and S2 .

There's one more thing you should remember about this is that if you pass by value, you can call functions and procedures with constants (such as 5 for integers, 'abc' for strings, ...) but if you pass by reference, you have to provide the variable(s) when calling your functions/procedures.

est69dog 0 Newbie Poster

thx

mahmoud85 0 Newbie Poster

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.