By Value VS By Reference: A Beginner's Perspective
One of the most important concepts of programming is the distinction between passing by value and passing by reference. In this post, I will try my best to explain the concept as I understand it as a beginner.
Passing by Value
Making a change to the variable d would not result to a change in the value stored in variable a as it is set to the value of 5 rather than the location variable a is stored. This is because in as much as the variable d points to the value stored in the variable a, it actually holds an entirely different value.
Passing by Reference
The other way by which variables can be stored is by Reference. This refers to when a variable been stored at a particular memory location on the local device. Arrays and objects are typically stored by reference to a particular memory location. A change made to the variable affects all other variables which point to that memory location. For example:
Making a change to variable g also changes to the value of variable f because the variable f (and by extension variable g )holds a reference to the memory address(say 0x00) rather than the array itself. The value of the array is however stored at this memory address, 0x00.
If you however assign variable g to a different array of numbers, this array would be stored in a new memory address(say 0x01). This allows you to overwrite the previous memory location set in the declaration( as in the previous block of code). The block of code below explains further:
It’s also worth noting that checking equality on two arrays that have the same exact values but do not reference the same memory locations returns false. Equality checks only return true if both arrays are stored at the same memory location.
The concepts of passing by values and passing by references in programming are important as it could lead to bugs that may be somewhat difficult to track down. Understanding this concept helps to save you time and effort when debugging your code.