Passing by reference VS Passing by value Flashcards
What is passing by value?
The value created for the subroutine is a copy of the original value.
What is passing by reference?
A pointer that contains the memory address of the original variable is created
This means that any change made to the variable in the subroutine also affects the original variable.
Features of passing by value
The copied value has its own separate memory
Seen more in newer programming languages
1 positive and 1 negative of passing by value
+ The copied variable and the original can be given the same identifier
- Creates inconsistency between the two variables
When would you pass by reference?
If the original value needs editing
When would you pass by value?
If it’s local and merely referenced
Features of passing by reference?
Uses a pre-existing memory location to store the memory address of the value.
Any edits directly affect the variable
1 Positive and 1 negative of passing by reference
+ Requires less space than passing by value
- Entails implicit dependency, which is considered bad practice.
How is implicit dependency triggered in passing by reference?
If you pass a local variable by reference and then assign to it, the result is a direct change to the caller’s variable, not to what its pointing to.