Erel B4X founder Staff member Licensed User Longtime User Mar 14, 2021 #21 Quiz (x and y are local variables): Code: Dim x As Int = 3 Dim y As Int = 4 Swap(x, y) Log(x) Log(y) What is the output?
Quiz (x and y are local variables): Code: Dim x As Int = 3 Dim y As Int = 4 Swap(x, y) Log(x) Log(y) What is the output?
pliroforikos Active Member Licensed User Mar 14, 2021 #22 Swap means that now x points to 4 and y points to 3 So we see 4, 3
pliroforikos Active Member Licensed User Mar 14, 2021 #23 Thank you now i have enough information to write about lists.
Erel B4X founder Staff member Licensed User Longtime User Mar 14, 2021 #24 Code: Sub Swap (xx As Int, yy As Int) No. x points to an int object with the value 3. 3 is an immutable object. Like all other cases, a copy of the pointer is assigned to the xx parameter. No matter what will happen inside Swap it cannot affect the pointer stored in x which will always point to the object 3. The output will always be: 3 4 If we want to create a Swap sub then we must use mutable objects: Code: Type IntHolder (Value As Int) Dim x As IntHolder = CreateIntHolder(3) Dim y As IntHolder = CreateIntHolder(4) Swap(x, y) Log(x.Value) '4 Sub Swap (xx As IntHolder, yy As IntHolder) Dim t as Int = xx.Value xx.Value = yy.Value yy.Value = t End Sub Another example: Code: Dim x() As Int = Array As Int(3) Dim y() As Int = Array As Int(4) Swap(x, y) Log(x(0)) '4 Sub Swap (xx() As Int, yy() As Int) Dim t As Int = xx(0) xx(0) = yy(0) yy(0) = t End Sub Note that x and y point the same two objects all the time. We modify these objects internal values.
Code: Sub Swap (xx As Int, yy As Int) No. x points to an int object with the value 3. 3 is an immutable object. Like all other cases, a copy of the pointer is assigned to the xx parameter. No matter what will happen inside Swap it cannot affect the pointer stored in x which will always point to the object 3. The output will always be: 3 4 If we want to create a Swap sub then we must use mutable objects: Code: Type IntHolder (Value As Int) Dim x As IntHolder = CreateIntHolder(3) Dim y As IntHolder = CreateIntHolder(4) Swap(x, y) Log(x.Value) '4 Sub Swap (xx As IntHolder, yy As IntHolder) Dim t as Int = xx.Value xx.Value = yy.Value yy.Value = t End Sub Another example: Code: Dim x() As Int = Array As Int(3) Dim y() As Int = Array As Int(4) Swap(x, y) Log(x(0)) '4 Sub Swap (xx() As Int, yy() As Int) Dim t As Int = xx(0) xx(0) = yy(0) yy(0) = t End Sub Note that x and y point the same two objects all the time. We modify these objects internal values.