Passing Variables by Reference and Value

I recently covered soft and hard links in Linux, and figured it would be a good idea to follow up with passing variables into functions by reference and value. Every variable is assigned a memory address, just like files in Linux. Just like linking those files in Linux, you can do two different things with that information. The first thing you can do is pass that address into a function to copy its value, and then manipulate that value in the function. The result of that operation is a new value based on the copy of the old value. This is called passing a variable by reference. Much like hard links this is typically the safer and non-destructive way of handling information. The alternative approach is to pass the variable by value.

Passing a variable by value means to access the memory address of the variable and alter that value directly. The end result is that the variable’s value will be altered outside of the scope of the function. This is a destructive approach to altering information because the original information is gone. However, that can sometimes be necessary when you’re passing that new value off to other functions for more processing. It’s kind of weird to think about at first, but pretty straightforward once you get used to it all. This is a pretty watered down explanation, but it should work for most cases.

If you buy anything from Amazon using the link below I may receive a commission from your purchase at Amazon.
Tech Best Sellers at Amazon

Leave a comment

Your email address will not be published. Required fields are marked *