By Value or by Reference

Parent Previous Next

By Value or by Reference.

When passing arguments to a function it can be done by value or by reference (specified with the & symbol). Here we present a few scenarios which should exemplify, what happens for standard types, classes and arrays:


Standard Types.


 Function Foo1(Integer X { X := 1; } //By value

 Function Foo2(Integer &X) { X := 2; } //By reference


 Function Test()

 {

   Integer Q; //Q == 0;

   Foo1(Q);   //Q remains 0;

   Foo2(Q);   //Q is now 2;

 }



Classes.


Class TType

{

 Public Integer Field;


 Function Foo1(TType X { X.Field := 1;  X.New().Field := -1; }

 Function Foo2(TType &X) { X.Field := 2;  X.New().Field := -1; }


 Function Test()

 {

   TType Q;

   Q.New();  //Now Q.Field == 0;

   Foo1(Q);  //Now Q.Field == 1; Q still refers to the same object.

   Foo2(Q);  //Now Q.Field == -1 and Q refers to a new object.

 }

}



Arrays.


 Function Foo1(Integer[] X { X[].Add(3);  X[].New().Add(-1); }

 Function Foo2(Integer[] &X) { X[].Add(4);  X[].New().Add(-1); }


 Function Test()

 {

   Integer Q[].New();

   Q[].Add(1); //Now Q ~ [1]

   Q[].Add(2); //Now Q ~ [1, 2]

   Foo1(Q[]);  //Now Q ~ [1, 2, 3]

   Foo2(Q[]);  //Now Q ~ [-1] and refers to a new object.

 }



Conclusion: Custom types passed by reference like &X  can be permanently redirected to a new object in memory.