Function Call by Reference

Hi I am trying to pass a float[][] matrix by reference and change its value. However, the returned value is not being changed. In general, any array or matrix must be treated as call by reference for any function in java/c++/ Please correct me if I am wrong. I am attaching the source code. It uses the Papaya Library. I really need urgent help.

Chandra:-$ :(

`import papaya.*;`
    void changevalue(float[][] R)
    {
     R=papaya.Mat.sum(papaya.Mat.identity(3),R);
     papaya.Mat.print(R,4);

    }

    void setup()
    {

    float[][] R1_p=papaya.Mat.identity(3);
    changevalue(R1_p);
    papaya.Mat.print(R1_p,4);
    }

Answers

  • Nope, that's not how Java works. Java is always pass by value. It might get confusing because Java passes the value of a reference, but the point is that you can't do what you're trying to do.

    You either have to wrap it up in another Object, or manipulate the array directly.

  • edited October 2014

    Java is pass-by-value

    try use the return value instead, to get something out of the function:

    float[][] changevalue(float[][] R) { 
    // .....
    return R
    }
    
  • edited October 2014

    As mentioned many times above already, Java only sends the value stored in a variable (or the result of an expression) to the parameters of a function! That is: "pass-by-value"!

    What folks can get confused about is related to the fact "value" can either be primitive or reference/pointer.
    When that "value" happens to be a reference, folks tend to call it "pass-by-reference". Which isn't entirely true!

    Real "pass-by-reference" is when we send the reference/pointer/memory address of the variable being passed instead of the value stored in it!

    In C/C++/D and similar, they've got the unary operator &, which "captures" the memory address of a variable.
    By sending the variable's reference to the function, it can reassign another value to that variable!

    However, Java/JS and many other modern languages don't provide such powerful feature anymore!
    Which means we can't change the value of a passed variable anymore!

    If the passed value is a reference to an object, we can manipulate that object to our heart's content.
    But we can't assign another object reference to the passed variable per se!

  • An attempt fix: (*)

    // forum.processing.org/two/discussion/7509/
    // function-call-by-reference
    
    import papaya.*;
    
    static final float[][] getNextSum(float[][] r) {
      return Mat.sum(Mat.identity(3), r);
    }
    
    void setup() {
      float[][] r1 = Mat.identity(3);
      r1 = getNextSum(r1);
      Mat.print(r1, 4);
      exit();
    }
    
  • Answer ✓

    Note that if you change the values in R (individually), the array on the call site will be changed as well. You just can't change the whole array at once.

Sign In or Register to comment.