Sunday, August 2, 2009

C++ help please?

NOTE: Please do not hook me up with links. Rather, explain the question as best you can. (I have plenty of links; they don't seem to help).








In detail, what is the difference between call by value and call by reference parameters?

C++ help please?
When a function is called, a so-called stack frame is created. This is a subset of the program's stack, and it contains the variables that are local to the function. When the function ends, the changes to the stack frame are thrown away.





There are actually two ways that the stack frame can contain the local variables. It can contain the actual value of the variable (or constant) that was used to call the function, OR it contains the address of that variable (in other words: a reference to that variable).





In the former case (call by value), changes made to the variable by the function are discarded when the function terminates (because the stack frame is thrown away). In the latter case (call by reference), the changes that are made, are made to the actual variable that was used to call the function --because of this, when the stack frame is thrown away, the change to the calling variable persists.





Note that you cannot initialize a reference parameter with a constant value, like this:





void foo(int%26amp; bar)


{


   bar++;


}





main()


{


   foo(5);


}





because changes to the reference variable bar would have to have a persistent effect on the constant 5, which is obviously not possible (you can't change a constant value).





Does that help?
Reply:Too wordy???? Then don't say you want an answer 'in detail'. Report It

Reply:You don't want links because you have plenty of them. So I came up with an unusual explanation, or else I'd just be telling you what you've already read before.


You write you want detail. I give it and as a thank you, you give one star saying it's too wordy.


Geesh. Report It

Reply:in call by value only value is passed





in call by reference the entire address of the memory where the value is stored is passed so changes are reflected.
Reply:Your question limitations demonstrate the answer.


Call by reference is like an answer of a link.


Call by value is like like an answer of actual text.





Ref is smaller(and faster call), value is larger (and slower call)


At the callee, changing the value parameter does not affect the original, but the original CAN be altered through a ref parameter.





Hope that is sufficient.


No comments:

Post a Comment