Q. Name and differentiate the following two constructs:
For (auto e: myContainer) and for (auto &e: myContainer)
Explain the situation where one construct is preferred to the
other.
Give an example
usage.
I got the
following answer here at Chegg but I still need an example (simple
one) please:
1st one is call by value when you want use it for read only purpose
than use this cal by value
2nd one is call by reference. we will use this when we want to
modify the parameters Usage:
we will use call by reference when we want to return the mulitple
values from a function
Call by value:
In this, only the value of a parameter is passed, and not the parameter itself. We may change the value in any way we like but it won't affect the original parameter.
For example, consider the below snippet.
void func(int n)
{
//function workings
}
main()
{
int m = 5, p;
p = func(m);
}
In this, only the value of m is passed to func, and not the address. Suppose m is stored at position 2001 in the memory. Thus, 2001 has the value 5 in it. In call by value, only this 5 is passed, and not 2001. Thus, the variable n in func maybe in position 7867. Modifying n in func will change the value at memory position of 7867, but not 2001. Thus the original parameter will remain unchanged.
Call by reference:
Unlike call by value, the memory address itself is passed to the function. As the memory address has the value of the original parameter, any change in the function will reflect on the original.
For example, consider the below snippet.
void func(int &n)
{
//function workings
}
main()
{
int m = 5, p;
p = func(&m)
}
In this, the address of m is passed to the function. Again, suppose m is stored at memory address 2001. In call by reference, this 2001 itself is passed to the function. So n has value 2001. Thus, changing anything will change the value at address 2001, and thus the original parameter will be changed.
When to use which?
Call by value is mainly used to read and perform operations with the data. On the other hand, call by reference is used when along with reading and performing an operation, we also need to write something in the parameter. However, we must be careful while using call by reference because otherwise any error may cause data corruption.
In case of any doubt, drop a comment and I'll surely get back to you.
Please give a like if you're satisfied with the answer. Thank you.
Get Answers For Free
Most questions answered within 1 hours.