Loading...
Logo
Processing Forum

 

Hello,

when a function is called with parameters I normally can say "call by value" or "call by reference".

Question: 1. What is the default in processing, call by value or call by reference?

2. How can I tell my function to use "call by value" or "call by reference" for a parameter?

Explanation: call by value = only the value of the variable is given as a parameter. When you change the value in the function, nothing happens to the variable in the structure that calls our function.

call by reference = the reference to the variable is given as a parameter. This is the normal case. Anything the function changes with it, goes right back to the variable in the structure that calls our function.

That's the way I know it from visual basic.

Thank you!

Greetings,

Chrisir

 

Replies(2)

Isn't this fairly straightforward to test?  E.g:

Copy code
  1. int intVar = 0;
  2. String stringVar = "a string";
  3. int[] arrayVar = {1,2,3,4};

  4. void setup() {
  5.   changeInt(intVar);
  6.   println(intVar);
  7.   changeString(stringVar);
  8.   println(stringVar);
  9.   changeArray(arrayVar);
  10.   println(arrayVar);
  11. }

  12. void changeInt(int intIn) {
  13.   intIn = 1;
  14. }

  15. void changeString(String stringIn) {
  16.   stringIn = "nothing...";
  17. }

  18. void changeArray(int[] arrayIn) {
  19.   arrayIn[0] = 9;
  20.   arrayIn[1] = 8;
  21.   arrayIn[2] = 7;
  22.   arrayIn[3] = 6;
  23. }
Technically I think Java parameters are always passed 'by value', but you'll see that in practice in Processing, that's not always the behaviour you see - i.e. changing the array within the function does affect the original.  I'm sure one of the Java experts can explain why :/
When you know that Processing is mostly Java, a little Google search gives lot of information about this. Although part of it is wrong...
I think one of the best (complete, correct) article on the topic is:  Java is Pass-by-Value, Dammit!
As the title says... In short (bad explanation, see original!): You can assign a new value to a parameter of a function (some languages prefer to make them immutable) but the caller of the function won't see the change. But if you alter the value (if the parameter is an object, including arrays), the change will be seen by the caller: the reference to the object hasn't changed, the content pointed by the reference can change.