+ 1
"In pass by alias/reference, can the calling method pass a value?"
Answer: No. I'm unfamiliar with the term "pass", "alias/reference", "calling method". What do these terms mean/do they have a more familiar/common name, and why is the answer no?
3 odpowiedzi
+ 3
Call/Pass by Value is a method where you pass a 'copy' of the variables inserted into the functions as arguments to be used in a function...
Eg -
void swapv(int a,int b)
{
a+=b;
b=a-b;
a-=b;
cout<<a<<":"<<b<<endl;
}
main()
{
int a=2,b=4;
swapv(a,b);
cout<<a<<":"<<b<<endl;
}
This prints
4:2
2:4
So, now, pass by value hasn't changed the original a and b from main...
Thus, we have pass by alias/reference,which passes the address of the arguments into the parameters...
This prevents the function from making a copy, as the variable at the same address is altered...
Eg-
void swapr(int& a,int& b)
//& is the reference operator, used to get the address of a variable...
{
a+=b;
b=a-b;
a-=b;
cout<<a<<":"<<b<<endl;
}
main()
{
int a=2,b=4;
swapr(a,b);
cout<<a<<":"<<b<<endl;
}
This prints
4:2
4:2
Now, calling is simply defined as the use of the function in main...
Now, in the call by value swap, you can even call the function like this:
swapv(2,4);
//No variables, just rvalues, which are temporary...
//Prints 4:2...
But this leads to an error:
swapr(2,4);
This is as the values passes here are temporary, and have no set address to alter them in memory...
They have no fixed representation and thus cannot be altered...
Thus, the answer here is no...
+ 3
You're Welcome! ^_^
+ 1
Wow, thank you for this!!