In: Computer Science
It is a C++ introduction exercise and I am a rookie. Please contain detailed reasons and explanations and I would appreciate any help you can provide.
When we pass parameters to functions by value or by reference, we're doing different things; the end result will not necessarily be the same. And, of course, it's wise for us to understand exactly how the results will be different. But another angle we need to consider is why we need to have these two different kinds of parameters, which is to say that we should understand when we would be better off using one technique instead of the other.
1. What are the design benefits of passing a parameter by value? What can you do when you pass by value that you can't do when you pass by reference?
2. What are the design benefits of passing a parameter by reference? What can you do when you pass by reference that you can't do when you pass by value?
3. Suppose you were going to write a function with one parameter, and that the result would be the same whether you passed the parameter by value or by reference — it's not always the case that the outcome will be different. In what circumstances would you expect the pass-by-value version to run faster? In what circumstances would you expect the pass-by-value version to use less memory?
4. Same situation as the previous question. In what circumstances would you expect the pass-by-reference version to run faster? In what circumstances would you expect the pass-by-reference version to use less memory?
Note that these questions are not about how these techniques work, they're about why you would prefer one rather than the other.
Explanation
In single argument case-Passed parameters by value or by reference, we are doing differentn things and the end result will not be the same a
1. benefit of passing by value
In call by value, original value is not modified.
2. benefit of passing by reference
Actual and formal arguments will be created in same memory location in pass by references
3. suppose we are going to write with one parameter, do it by value or reference
PASS BY REFERENCE
#include <iostream>
using namespace std;
void change(int* NUM)
{
*NUM = 5;
}
int main()
{
int NUM = 3;
change(&NUM);
cout << "Value of the data is AFTER FUNCTION CALL: " << NUM<< endl;
return 0;
}
4. pass by reference
This method is also called as call by reference. This method is efficient in both time and space.
PASS BY VALUE
1. LIMITATION
Inefficiency in storage allocation
For objects and arrays, the copy semantics are costly
Conclusion:
Pass-by-reference makes some things more efficient and allows updates to parameters within subroutines.
where as pass-by-value is much easier to make memory safe and efficient. If you pass pointers/references to stack-allocated memory, you need to make sure the memory outlives the reference. If you instead use automatic memory management to ensure that, you pay a run-time price for that.