Search code examples
javac++clone

Struct value storage


I am converting a program originally in C++ over to Java, since I have little experience with C++, and am having some problems.

struct indx{ int i,j; };
void increment(indx place) { 

    place.i+=5;
    place.j+=5;

}

When C++ passes structures through methods and modifications are made, are they maintained in the rest of the code? In Java terms, will modifying a struct in a method be the same as modifying a clone?


Solution

  • You're passing place by value which means increment is operating on a copy of your structure, not the original. Change to pass-by-reference, like this:

    void increment(indx& place) {
    ...
    }
    

    The function will then be operating on the original structure and any modifications will persist back to the caller.