We are about to switch to a new forum software. Until then we have removed the registration on this forum.
In Pascal, i heard about something like this:
program abc;
var x,y:integer;
procedure something(a,b:integer);
var c:integer;
begin
c:=a;
a:=b;
b:=a
end;
begin
a:=3;
b:=5;
{now a=3, b=5}
swap(a,b);
{now a=3, b=5}
end.
but if you were to add "var" before the parameters:
program abc;
var x,y:integer;
procedure something(var a,b:integer);
var c:integer;
begin
c:=a;
a:=b;
b:=a
end;
begin
a:=3;
b:=5;
{now a=3, b=5}
swap(a,b);
{now a=5, b=3}
end.
I wonder how can i achieve the same result? I also wonder what this problem is called.
Thanks in advanced for helping me.
Answers
https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text
In Java all variables passed to functions are copies of their current value. ~O)
Thus Java can't reassign caller's variable(s) to something else inside a function. [-X
@GoToLoop
Could you define the parameters of the function to be final? Then you are forbidden to modify the parameters inside the function?
@157239n
EDIT---- I don't know how this is named in Pascal, but in C++ for example, you are passing values either by value or by reference. Your first case is by value and your second case is by reference. When you pass it by reference, any modification you do inside the function to those values, they will be retained after you leave the function. For the first case, parameters by value, the function passes an actual copy of the parameters, the function executes and modify those values and at the end of the function they are discarded as there were copies in the first place.
Kf
@kfrajer, like I've explained, function's parameters receive copies of the values sent.
Sealing them up w/
final
wouldn't change a thing, b/c they're merely copies. ^#(^@GoToLoop Right... I misread your post so disregard my last comment.
Kf
No problem. I didn't express it well either! Just edited it now. 8-|
This is a really good site that describes the reference concept:
http://javadude.com/articles/passbyvalue.htm
from
http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value
Kf
@kfrajer's first link explains it fully.
While you cannot swap variable references or reassign object pointers, you can pass in reference values (pointers) and use a function to:
So
void swap(PVector a, PVector b)
orint[] swap (int[] array, int idx1, int idx2)
are both possible. Note however thatvoid swap (Integer a, Integer b)
won't work because Integers are immutable.For long (and sometimes funny) discussions of various ways of doing this:
The top answer in every thread is an int-swapping hack that uses an assign-in-a-throwaway-argument trick.
This usage works... but is a hack. Probably better to just swap values manually in your code using a temp variable.
Yeah. Use temp variables. It is not much work, but has better performance than those swap functions.