#Hello, how do I make changes to a variable given to a method so that they reflect on everything?

8 messages · Page 1 of 1 (latest)

iron widget
#

Trying to add stuff into an array with custom methods(low level/beginner stuff), but the changes dont get reflected, for example if I make a swap program, which switches values of a and b:

        int c=0;
        c=a;
        a=b;
        b=c;
    }```
when I print them in main, no change is reflected, how do I make it so that changes are reflected?
rugged obsidianBOT
#

This post has been reserved for your question.

Hey @iron widget! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

fervent grove
#

you're just swapping around the variables a and b here, those only exist in swap and get discarded when the method ends. it doesn't have any effect on whatever variables you fed to swap.
assuming you're trying to swap 2 elements of an array, instead pass the entire array so you can mutate the array
if you assign into the array, that will have an effect on the array outside the method

iron widget
#

so if its an array that I fed the method, there will be changes reflected on whatever I do inside or did I get it wrong?

fervent grove
#

yes, because mutation doesn't just reassign the local variables of the method, it affects the contents of the object passed
the entire integer is passed here, but you're just moving the integer around inside the method, no effect outside
but with an object, the entire object is also passed, but you're moving its contents, and that's still the same object as you passed in, so outside the method you see the changes to the object's contents

iron widget
#

Thanks for the information and help, have a nice day

rugged obsidianBOT