What are the two ways to pass by reference? b. What behavior can be confusion wh
ID: 3848254 • Letter: W
Question
What are the two ways to pass by reference? b. What behavior can be confusion when calling a function directly within a cout statement? c. If you name a local variable in a calling program the same name used as a parameter name, will their addresses be the same? Under what conditions would a local variable and an argument in a function have the same address? d. Research the internet looking for opinions posted by other programmers on when to use pointers and when to use reference variables. Could you find any advice that seemed useful and/or was commonly suggested?
Explanation / Answer
[a] In Pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.
[1] passing the argument variable itself and inside function use address.
void foo(int &value)
{
value = 6;
}
int main()
{
int value = 5;
cout << "value = " << value << ' ';
foo(value);
cout << "value = " << value << ' ';
return 0;
}
[2] passing the address of the argument variable rather than the argument variable itself
#include <iostream>
void foo(int *ptr)
{
*ptr = 6;
}
int main()
{
int value = 5;
std::cout << "value = " << value << ' ';
foo(&value);
std::cout << "value = " << value << ' ';
return 0;
}
---------------------------------------------------------------------------------------------------------------------------------------------
[b] The order of evaluation of arguments to a function is unspecified.
---------------------------------------------------------------------------------------------------------------------------------------------
[c] The variable in main() method and a Same name variable in method parameter, but they have different addresses, which means that they are not the same variable.Pass the variable's address to the function instead of the variable's value, Both Variable address are Same.
----------------------------------------------------------------------------------------------------------------------------------------------
[d]Pass arguments by reference:
Case 1 : For passing large sized arguments
Case 2 : To achieve Run Time Polymorphism in a function
Case 3 : To avoid Object Slicing
Pass arguments by pointer:
Case 1 : If the function needs to modify its parameter;
Case 2 : If copying the variable to the stack to pass it to the function is expensive.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.