Issue
Consider the following function prototype:
swap(int &a,int &b);
'x' and 'y' are two integers local to main function.
Assume that the control is in main() function.
Now,when the compiler encounters this type of statement:swap(x,z);
What does actually happen underneath the hood(I mean,in terms of memory locations)?
My questions are:-
- Is there any memory allocated for a,b in swap() function's stack?If allocated ,what would it store?
- How does call by references work?
Solution
Is there any memory allocated for a,b in swap() function's stack?If allocated, what would it store?
First, consider the answer to the same question in a call to swap_ptr(int *a, int *b)
Assuming that stack is used for passing parameters, some memory would be allocated to a
and b
in a call to swap_ptr(&x, &y)
. That memory would hold pointers to x
and y
.
The same thing happens when you pass references: some memory is allocated on the stack to pass references a
and b
, and initialized with references to x
and y
. This memory often has layout identical to a pointer, but the standard does not require this: the structure used for passing references is implementation-specific and non-transparent.
How does call by references work?
In the same way that call by value works, except the compiler knows to construct a reference, rather than making a copy of the object being passed.
Answered By - Sergey Kalinichenko Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.