Pass by value and pass by reference

I've recently been reading on pass by value and pass by reference, and I understand the difference between them, but I don't understand why they are used and when do you use them?
You have to understand that when you pass a variable to a function, you're not just "giving" the variable to the function. But rather allowing the function to copy the contents of the variable passed onto a set of local variables.

And these local variables are variables that will just "cease to exist" after the function is exited.

Problem arises when you either want to prevent copying of contents of passed variable onto local variables (because copying can be expensive and you want to be more efficient) or when you want to just directly change the value of a variable WITHOUT having to return a value and assign this value to a variable in the main function.

When would you want to directly change the value of a variable?

Suppose you pass an array of integers to a function and want to increment each index by 1. How would you do this? You would have to pass the array, copy the passed array onto a separate array inside the function and then do the required which is to increment each index, and then finally return this new array which will then be assigned to the original array in the main function.

But passing the array by reference would make it so that the original array indexes are directly incremented instead of having to do any assigning or copying.
Last edited on
Topic archived. No new replies allowed.